There are four types of conversions:
Implicit conversion
Explicit conversion
Custom conversion
Conversion with helper class/method
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;
In case of not "Type safe", we can use explicit conversion.
double x = 123.45;
int y = (int) x;
// this is allowed (refer Explicit Numeric Conversion in C# Reference).
or 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.
User defined conversion is a custom way of conversion by define an operator, look
the following code:
class TypeA
{
public static explicit operator SampleClass(TypeB b)
{
TypeA temp = new TypeA();
// code to convert from TypeB to TypeA
return temp;
}
}
In addition, .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. the
handle it, there are ways to walk around. See the following code:
I will introduce:
1. Use As operator
2. TryParse method.
No comments:
Post a Comment