Type Conversion and Conversion Operators in C#


What is Conversion?
Conversion is the process of changing a value from one type to another. Conversions may either be widening or narrowing:

Widening conversions: When a particulardata type is converted to a data type that is capable of storing moredata than the source data type is referred to as widening conversion.The simple examples of widening conversion can be Numeric typeconversions in the direction Byte, Short, Integer, Long, Decimal,Single, Double, here every type listed to the right of a type iscapable of storing more data than its left listed type. If we takes thecase of reference data types then Conversions from any derived type toone of its base types is also referred to as widening conversion.Widening conversion never cause overflow.

Narrowing conversions: A narrowingconversion occurs when a variable is converted to a type that is notcapable of storing the data held by the source data type variable.These conversions are known to possibly lose information, andconversions across domains of types sufficiently different to meritnarrowing notation. These means narrowing conv

ersions entail loss of information and may fail.Following list defines different types of conversion:Identity conversion: An identity conversion converts from any type tothe same type. This conversion exists only such that an entity thatalready has a required type can be said to be convertible to that type.

Numeric conversions: Some examples of numeric conversions are:
? From sbyte to short, int, long, float, double, or decimal.
? From byte to short, ushort, int, uint, long, ulong, float, double, or decimal.
? From short to int, long, float, double, or decimal.
Etc.

Reference conversions: These areconversion from one reference type to another. Reference conversions,implicit or explicit, never change the referential identity of theobject being converted. In other words, while a reference conversionmay change the type of the reference, it never changes the type orvalue of the object being referred to.

Boxing and Un-boxing conversions: Aboxing conversion permits any value-type to be converted to the typeobject or to any interface-type implemented by the value-type. Boxing avalue of a value-type consists of allocating an object instance andcopying the value-type value into that instance. Unboxing is anexplicit conversion from the type object to a value type or from aninterface type to a value type that implements the interface. Anunboxing operation consists of:
- Checking the object instance to make sure it is a boxed value of the given value type.
- Copying the value from the instance into the value-type variable.

Interface conversion: Converting aninterface to a value type consists of copying the value in theinterface instance to the target variable (which may be a temporary).

Conversion operators:
C# allows the pre-defined implicit and explicit conversions to beaugmented by user-defined conversions. User-defined conversions areintroduced by declaring conversion operators in class and struct types.

The most commonly used conversion operatorthat is available in language is parentheses. In addition to being usedto specify the order of operations in an expression, parentheses areused to specify casts (type conversions):

For e.g.:
double x = 1234.7;
int a;
a = (int)x;

Parentheses are mostly used to carry out theconversions where one is sure about the types he or she dealing with.Conversions can fail when the types are incompatible or also can resultin the loss of data in case of narrowing conversions.

In addition to the inbuilt conversionfunctionality, we can define our custom conversion functionality touser-defined types by having a conversion function in a class orstruct. These conversions functions can be written to provide eitherexplicit or implicit conversion functionality, for this purpose C#provide with the keywords implicit and explicit.

Implicit conversion:
The implicit keyword is used to declare an implicit user-defined type conversion operator.

class SomeType
{
public static implicit operator int(SomeType typ)
{
// code to convert from SomeType to int
}
}

Implicit conversion operators can be called implicitly, without being specified by explicit casts in the source code.

SomeType x;
int i = x; // implicitly call SomeType's implicit conversion function that returns int value.

Since the implicit conversion occurs with out user specifying the casting type, may sometimes lead to confusing code.

The following implicit conversions are classified as standard implicit conversions:
? Identity conversions
? Implicit numeric conversions
? Implicit reference conversions
? Boxing conversions
? Implicit constant expression conversions
The standard implicit conversions specifically exclude user-defined implicit conversions.

Explicit Conversions:
Explicitconversion is performed using casting. Casting occurs when you prefix aconversion with a data type that defines the type of the conversion youwant to perform. The explicit keyword is used to declare an explicituser-defined type conversion operator. The set of explicit conversionsincludes all implicit conversions.Example:

class SomeType
{
public static explicit operator SomeType (int i)
{
// code to convert from int to SomeType
}
}

Unlike implicit conversion, explicit conversion operators must be invoked via a cast.

int i;
SomeType x = (SomeType)i;

Omitting the cast results in a compile-timeerror. Using explicit prevents the compiler from silently invoking theconversion operation with possibly unforeseen consequences.

The following conversions are classified as explicit conversions:
? All implicit conversions.
? Explicit numeric conversions.
? Explicit enumeration conversions.
? Explicit reference conversions.
? Explicit interface conversions.
? Unboxing conversions.
? User-defined explicit conversions

References: MSDN

Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!