C# Programming/Casting

From Wikibooks, open books for an open world
Jump to: navigation, search

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

double dDistance = iValue ;

public class Animal { [] };

public class Mammal : Animal { [] };

public class Cat : Mammal
{
    […]
}

Mammal mammal = new Cat();

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

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;
}

References[edit]