Type conversion is a process where data of one type is converted into data of another type (Docs, 2015). C# has 2 forms of type conversions:
- implicit conversions
- explicit conversions (or type casting)
Implicit conversions
The conversions are performed by C# in a type-safe manner, most of which are widening conversion.
For example, conversions
from smaller to larger integral types
int num1 = 10;
double num2 = num1;
from derived classes to base classes
Derived d = new Derived();
Base b = d;
Explicit type conversion
Casting is required when information might be lost in the conversion, which is also known as a narrowing conversion. Explicit conversions require a cast operator in the form of (<target_type>)<data>
.
For example, conversions
from larger to smaller integral types
double num1 = 10;
// int num2 = num1; // error
int num2 = (int)num1;
from base class to child class
Derived d = new Derived();
Base b = d;
// Derived d2 = b; // error
Derived d2 = (Derived)b;
References
- Docs, M. (2015, July 20). Casting and Type Conversions (C# Programming Guide). Retrieved from https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/casting-and-type-conversions