C# Casting
Last modified: July 11, 2021In C#, there are two types of casting:
Implicit Casting (automatically) - from a smaller data type to a larger one
- char -> int -> long -> float -> double
Explicit Casting (manually) - from a larger to a smaller one
- double -> float -> long -> int -> char
Implicit Casting
static void Main(string[] args)
{
int numberOfBallsInABox = 12;
double numberOfBallsInABoxDouble = numberOfBallsInABox; //output 12
}
Explicit Casting
(int)doubleVar
convert to int without rounding but Convert.ToInt32(doubleVar)
convert to int and round up
static void Main(string[] args)
{
double doubleVar = 9.89;
int intVar = (int)doubleVar; //output 9
//OR
int intVar2 = Convert.ToInt32(doubleVar); //output 10
}