What is implicit and explicit casting in C#?
The conversion of one data type into another is known as type casting. There are two kinds of type casting in C#:
- Implicit casting
- Explicit casting
Implicit casting
The conversion of a smaller data type to a larger data type is known as implicit casting. It is done automatically. For example, if the short and int types are being added, the short data type will be converted to the int data type.
Explicit casting
The conversion of a larger data type to a smaller data type is known as explicit casting. To convert the decimal data type to the int data type, (int) is written before the decimal variable.
Note: Converting the larger data value to the smaller data type may cause some data loss.
Example
decimal firstNumber = 50.1234m;int secondNumber= 2;Console.WriteLine("Implicit casting:");Console.WriteLine(firstNumber + secondNumber); // Output: 52.1234Console.WriteLine((firstNumber + secondNumber).GetType()); // Output: System.DecimalConsole.WriteLine("Explicit casting:");// Explicitly cast firstNumber to int. Data was lost (.1234)Console.WriteLine((int)firstNumber + secondNumber); // Output: 52Console.WriteLine(((int)firstNumber + secondNumber).GetType()); // Output: System.Int32
Explanation
- Lines 1–2: We declare two variables of the
decimalandinttype. - Line 5: We print the result of the implicit casting by adding both variables.
- Line 6: We print the type of the addition with the
.GetType()method. - Line 10: We print the result of explicit casting by adding after the conversion of the
decimalvalue to theinttype. - Line 11: We print the type of the addition with the
.GetType()method.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved