C# Programming/Casting

< C Sharp Programming


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 castingEdit

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 = 4711;

double dDistance = iValue ;

public class Animal { [] };

public class Mammal : Animal { [] };

public class Cat : Mammal

Mammal mammal = new Cat();

Explicit castingEdit

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


double dPi = 3.1415926535;

object oPi = (object) dPi;

Best practicesEdit

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.

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