C# Programming/Casting

Casting

edit

Casting is a way to convert values from one type to another. Mainly, two types of casting exist, Implicit casting and Explicit casting. Boxing occurs when a value type is cast to an object, or reference type.

Implicit casting

edit

Implicit casting is the way values are cast automatically by the compiler. This happens if and only if no loss of information occurs. Examples can be seen when converting data from smaller integral types to larger types, or derived types to the base type.

int iValue = 5000;

double dDistance = iValue ;

public class Animal { [] };

public class Mammal : Animal { [] };

public class Cat : Mammal
{
    […]
}

Mammal mammal = new Cat();

Also, this example could work.

int num = 9513458219;
long bigNum = num;

Explicit casting

edit

This type of casting has to be specified by the developer, as a loss of data is possible.

double dPi = 3.1415926535;

int iValue = (int)dPi;   // iValue = 3
int iValue_2 = Convert.ToInt32(dPi);   // iValue_2 = 3

Boxing

edit
double dPi = 3.1415926535;

object oPi = (object) dPi;

Best practices

edit

For reference types, direct casting is discouraged unless the object is known to never throw an exception. A common best practice is to use the as keyword.

///<summary>
/// Function attempts to cast object to cat.  
/// If object cannot be cast to cat, returns null 
///</summary>
public Cat ConvertToCat(object obj)
{
   Cat c = obj as Cat;
   return c;
}

!Important: Using "as" keyword is the best practice only in case you are doing null check after the cast and then handle exception situation. In other cases better use explicit cast then debug a NullReferenceException

References

edit