Labs ICT
โญ Pro Login

Type Conversion

Sometimes you have a number stored as a string, or a string that looks like a number, and you need to convert it. This is called type conversion, and it is something you will do all the time in C#.

Why Do We Need Type Conversion?

Remember that Console.ReadLine() always returns a string? So if someone types "25", you get the string "25", not the number 25. You cannot do math with a string. Try this:

string age = "25";
// Console.WriteLine(age + 5);  // This gives "255", not 30!

See that? C# sees two strings and concatenates them instead of adding. You need to convert the string to a number first.

Converting Strings to Numbers

C# gives you several ways to do this:

// Method 1: Parse
string ageStr = "25";
int age = int.Parse(ageStr);

// Method 2: Convert class
double height = Convert.ToDouble("5.9");

// Method 3: TryParse (safer โ€” we will cover this later)
int result;
bool success = int.TryParse("42", out result);

Parse() works well when you are sure the string contains a valid number. But if it does not, your program crashes. TryParse() is safer because it returns a boolean telling you whether the conversion succeeded. We will learn more about this when we cover exception handling.

Converting Numbers to Strings

Sometimes you need to go the other way โ€” convert a number to a string so you can combine it with text:

int age = 25;

// Method 1: ToString()
string ageStr = age.ToString();

// Method 2: String interpolation (handles this automatically)
Console.WriteLine($"I am {age} years old.");

In most cases, string interpolation handles the conversion for you automatically. You rarely need to call ToString() explicitly.

Converting Between Number Types

You can also convert between different number types. Sometimes this happens automatically (implicit conversion), and sometimes you need to do it explicitly (explicit conversion):

// Implicit conversion (happens automatically โ€” no data loss)
int myInt = 10;
double myDouble = myInt;  // int โ†’ double is safe

// Explicit conversion (you must do it manually โ€” potential data loss)
double pi = 3.14159;
int rounded = (int)pi;  // double โ†’ int drops the decimal โ†’ 3

The general rule is: if the conversion might lose data, you need to do it explicitly. C# will not do it for you because it wants you to be aware of the potential data loss.

๐Ÿงช Quick Quiz

What happens when you do int.Parse("abc")?