C# Type Casting - Type Casting in C# with Examples
C# Type Casting - Type Casting in C# with Examples
- If the variable of one data type is changed to another data type is known as the Type Casting.
- Manually we can change the type of data, according to our needs.
- At the time of the compilation, C# is a statically-typed i.e., after the declaration of the variable, we cannot declare it again.
- The value of the variable cannot be assigned to another type of variable unless we implicitly change the type of the variable.
Types of Type Casting
Implicit Conversion
- There is no need for the special syntax, for the implicit conversion.
- This type of conversion is safe because, in this conversion, there is not any loss of the data.
- During implicit conversion include the conversion of the small type to large integral types, and from the derived class to the base class conversion.
Sample Code
Output
Explicit Conversion
- Explicit conversion will be done with the cast operator () and also includes the conversion of the base-class instance to the derived class.
- If the conversion is not succeeded, we will do the casting when there is the situation of the data loss.
- The example of the casting is the conversion of the numeric type to the small range or less precision.
Sample Code
Output
User-defined Conversion
- We can do this conversion by defining the method and we can use the technique to enable the explicit-implicit conversion between the custom type.
- In which does not have any relationship with the base-class or derived-class.