The conversion of one data type into another is known as type casting. There are two kinds of type casting in C#:
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.
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.
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
decimal
and int
type..GetType()
method.decimal
value to the int
type..GetType()
method.Free Resources