Friday, August 6, 2010

C# Type Conversion

Casting, conversion, type-safe, polymorphism, inheritance, boxing, so many thing that are related to type conversion. This artical shows conversions in following forms:


Implicit conversion
Explicit conversion
Custom conversion
Conversion with helper class/method

1. Implicit Conversion
int num = 12345;
long lnum = num;

It is a "type safe" conversion without losing anything in the process. The following example of converting from derived to base type also belong to this category:

//class Derived:Base{}
Derived d = new Derived();
Base b = d;

The typical use of implicit conversion is "up casting"

2. Explicit Conversion

In case of not "Type safe", we can use explicit conversion - the parentheses () operator:

double x = 123.45;
int y = (int) x;

this is allowed (refer Explicit Numeric Conversion in C# Reference). In case we need to convert a base type back to derived type:

Derived d1 = new Derived();
Base b = d1;
Derived d2 = (Derived)d1;

Note, when implicitly convert derived type to base type, because it is a reference type, the data or the object is not changed, just the way of accessing it changed. That is why we can explicitly convert back to derived type.

The typical use of explicit conversion is "down casting"

3. Custom Conversion

User defined conversion is a custom way of conversion by define an operator, look the following code, it is a conversion totally up to the developer:

class TypeA
{
public static explicit operator SampleClass(TypeB b)
{

TypeA temp = new TypeA();
// code to convert from TypeB to TypeA
return temp;
}
}

4. Conversion Helpers

.Net framework provided helper classes or methods for data type conversion, such as System.BitConverter class, System.Convert class, Parse method with built-in types like Int32.Parse.

With explicit conversion, system may raise InvalidCastException exception. if you want to keep it quiet, use "as" operator or TryParse method.

with "as" operator, instead of throwing an exception, for invalid type conversion, it return null value. e.g.,

SubClass s = superClassInstance as SubClass; // s is null

Doing differently, TryParse method return a bool indicating wether conversion is successful. if it succeeds, it exposes the result through a "out" parameter. e.g.,

int number;
bool r = Int32.TryParse("abc123", out number); // r is false, var number's value not changed.

No comments: