What are the 2 kinds of data type conversions available in C#?
Short answer
C# supports two kinds of data type conversions called implicit conversions and explicit conversions.
Advertisement
AModel answer
C# supports two kinds of data type conversions called implicit conversions and explicit conversions. Implicit conversions happen automatically and safely, without any risk of data loss, such as converting an int to a double, while explicit conversions require you to manually specify the conversion using cast syntax, since they carry a risk of data loss or failure, such as converting a double to an int or converting between incompatible reference types.
int wholeNumber = 10;
double decimalNumber = wholeNumber; // implicit, always safe
double price = 19.99;
int roundedPrice = (int)price; // explicit, requires a castReal-world example
A calculation engine automatically widens an int value into a double implicitly when combining it with other decimal values, while requiring an explicit cast whenever a decimal result needs to be narrowed back down into a whole number.
Likely follow-ups
- What is the difference between an implicit conversion and an explicit conversion?
- Are there conversions that require calling a method instead of using a cast at all?
Related topics