Labs ICT
โญ Pro Login

Type Casting

Sometimes you have a value of one type but you need it as another type. Maybe you read a number from the console as a string, but you need to do math with it. Converting between types is called casting, and C# gives you several ways to do it.

Implicit Casting (Automatic)

C# automatically converts one type to another when there's no risk of losing data. This always goes from a smaller to a larger type โ€” like fitting a small box inside a bigger box:


int myInt = 100;
double myDouble = myInt;   // Implicit: int to double, works fine
Console.WriteLine(myDouble);  // Prints 100

// float to double also works
float myFloat = 3.14f;
double anotherDouble = myFloat;
    

Implicit casting works for: int โ†’ long โ†’ float โ†’ double, and also int โ†’ double. Data can never be lost this way.

Explicit Casting (Manual)

When you might lose data โ€” like converting a double to an int (which drops the decimal part) โ€” you need explicit casting. You put the target type in parentheses before the value:


double myDouble = 9.78;
int myInt = (int)myDouble;   // Explicit: double to int
Console.WriteLine(myInt);    // Prints 9 (the .78 is truncated, not rounded)
    

Explicit casting is telling the compiler, "I know what I'm doing, go ahead." But be careful โ€” you can lose data without getting any error.

The Convert Class

The Convert class provides more robust conversion methods. Unlike explicit casting, Convert rounds instead of truncating:


double myDouble = 9.78;
int myInt = Convert.ToInt32(myDouble);  // Rounds to 10
Console.WriteLine(myInt);  // Prints 10

string numberStr = "123";
int parsed = Convert.ToInt32(numberStr);  // String to int
Console.WriteLine(parsed);  // Prints 123
    

Convert.ToInt32 converts a value to an int. There are similar methods for other types: ToDouble, ToString, ToBoolean, etc.

Parse Methods

Every built-in type has a Parse method that converts a string to that type:


string ageStr = "25";
int age = int.Parse(ageStr);

string priceStr = "19.99";
double price = double.Parse(priceStr);

string flagStr = "true";
bool flag = bool.Parse(flagStr);

Console.WriteLine(age + 5);   // Prints 30 (it's a real number now)
    

Parse throws an error if the string isn't valid. For safer conversion, you can use TryParse, which returns true/false instead of crashing.

Try it Yourself โ†’

๐Ÿงช Quick Quiz

What is it called when you convert a smaller type to a larger type?