C-Sharp allows us to create variable of many types but does not allow us to assign the value of one type of variable into another type of variable after a variable is declared. This cannot be declared again or used to store value of another type therefore C-Sharp provides the flexibility for casting/Conversion.
- Implicit Conversion
- Explicit Conversion
- ‘is’ and ‘as’ Operators
- User Defined Conversion
There are no special syntax is required for implicit conversion because it is type safe and no data will be lost. One data type can simply be assigned to another. This include conversion smaller to larger integral types and derived class to base class.
Implicit conversion of derived class to base class is called Upcasting.
int i = 1258975896;
Derived class always contains all the members of a base classes so derived class object can access the base class variable without any problem.
Explicit conversion convert the data larger to smaller and conversion of base class to derived class by using a cast operator. In this conversion information might be lost or conversion might not be succeed for some reason if not succeed it raised an exception
Explicit conversion of base class to derived classes is called Downcasting.
‘is’ and ‘as’ Operators
C-Sharp also provide ‘is’ and ‘as’ operators which are helpful in performing explicit cast in an exception safe manner. The is operator checks whether the type being casted from is compatible to the type being casted to and returns a boolean value.
The ‘as’ operator checks the compatibility and if it’s ok it will perform the cast too. If the cast is not compatible or unsuccessful then the result will be null. The as operator can only be used with reference type we can use ‘is’ or ‘as’ operator for exception safe casting we should use ‘is’ operator if the target type is value type and ‘as’ operator for reference type.
User Defined Conversion
User Defined Conversion is performed by using special method that can define to enable explicit and implicit conversion between class to struct or basic data type and struct to class or basic data type. There are lot of helper classes and helper function available in C-Sharp to perform the frequently needed conversion.