C# Programming/Casting

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


Casting is a way to convert values from one type to another. Mainly, two types of casting exist:

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