C# Type Casting

Type casting means converting a value from one data type into another. This is very common when numbers of different types need to work together, or when text typed by a user must be turned into a number your program can calculate with.

Implicit Casting (Widening)

Implicit casting happens automatically when you convert a smaller type into a larger compatible type, such as putting an int into a double. Because no data can be lost, C# does the conversion for you without any extra syntax.

Implicit conversion int to double

int whole = 9;
double decimalValue = whole;   // automatic: int fits inside double

Console.WriteLine(decimalValue);   // Outputs: 9

Explicit Casting (Narrowing)

Explicit casting is needed when you convert a larger type into a smaller one, such as a double into an int. Because data can be lost, C# will not do it automatically. You must place the target type in parentheses in front of the value to confirm you accept the possible loss.

Explicit conversion double to int

double price = 19.99;
int rounded = (int) price;   // explicit cast, drops the decimals

Console.WriteLine(rounded);   // Outputs: 19
Note: Casting a double to an int does not round to the nearest whole number. It simply cuts off everything after the decimal point, so 19.99 becomes 19, not 20.

Direction of Casting

ConversionTypeAutomatic?
int to doubleWideningYes, implicit
double to intNarrowingNo, explicit
int to longWideningYes, implicit
long to intNarrowingNo, explicit

Converting With Built-In Methods

For converting between numbers and text, C# gives you the Convert class and handy methods like int.Parse. These are especially useful when reading user input, which always arrives as a string. The example below turns text into numbers and back again.

Using Convert and Parse

string input = "42";
int number = int.Parse(input);        // string to int
double asDouble = Convert.ToDouble(input);
string backToText = number.ToString(); // int to string

Console.WriteLine(number + 8);   // Outputs: 50
  • Use implicit casting when converting to a larger, safe type.
  • Use explicit casting with parentheses when data might be lost.
  • Use int.Parse or Convert.ToInt32 to turn text into a number.
  • Use ToString to turn a number into text.
  • Casting a double to int truncates rather than rounds.

Exercise: C# Type Casting

What happens when you cast a double to an int in C# using (int)myDouble?