Last modified on 19 April 2012, at 13:39

C# Programming/Casting

CastingEdit

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

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

ReferencesEdit