C# Type Casting - NetwaxLab

Breaking

Facebook Popup

BANNER 728X90

Wednesday, January 21, 2015

C# Type Casting

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 can not 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

Implicit 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.

Integral types

int i = 1258975896;
long p=i;

Reference types

Derived class always contains all the members of a base classes so derived class object can access the base class variable without any problem.

Implicit Conversion

Explicit Conversion

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 InvalidCastException.

Explicit conversion of base class to derived classes is called Downcasting.

Integer Type

long m=85;
int i=(int)m;

Reference Type

Explicit Coversion

‘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.

Input

Output

Output

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.

User Defined Conversion


----

No comments:

Post a Comment