All implicit conversions are allowed, if the
destination type can accommodate all possible values of the source type. It’s
called widening conversion. Like conversion from integer to double.
If the range or precision of the source type is more
than the destination than it’s called narrowing
conversion and requires explicit conversion.
System.Convert can be
used to covert between the types that implement System.IConvertable interface.
Type.TryParse and type.TryParseExact are new in
.NET.
Boxing and
Unboxing:
Boxing converts a value type to a reference type and
Unboxing converts a reference type to a value type.
Object A;
Int I=0, j=0;
A = (object)I;
//Boxing
j = (int)A; //Unboxing
How to
implement conversion in custom types:
Override ToString() to provide conversion to
string and Parse() to Create object from string.
Implement System.IConvertable
interface to provide conversion through System.Convert. Use this technique to
provide culture specific conversions.
Implement TypeConvert class
to enable design-time conversion for use-in visual studio.
Conversion operator can be also used to convert implicitly
or explicitly from one data type to another.
Public static implicit operator <Type A>
(<Type B>)
OR
Public static explicit operator <Type A>
(<Type B>)
Implementing
IConvertible interface:
Add
IConvertible to the type definition and visual studio will automatically add 17
different methods including GetTypeCode, ChangeType, and ToType for each base
method. Throw exception for those the conversion is invalid. After implementing
IConvetible interface you can simply use it like:
Type
A; bool B;
B =
Convert.ToBoolean(A);
Comments