Why convert types
Every value in C# has a type, and the compiler won't mix types freely. Sooner or later you need to turn a value of one type into another: a number into text to display it, a decimal into a whole number, or text typed by a user into a number you can calculate with. The lesson covers three conversions, each with its own tool.
If you know Java, you may reach for String.valueOf, Integer.parseInt or Double.parseDouble. None of these exist in C#. The C# tools are ToString(), a cast, and int.Parse, described below.
Number to string: ToString()
Every value has a ToString() method that returns its text form:
int age = 25;
string ageStr = age.ToString(); // "25"
Often you don't need it at all. When you join a string and a number with +, C# calls the conversion for you, so "Age: " + age works. Use ToString() when you want a string value on its own, such as to store it in a string variable.
Double to int: the cast
A cast is a type name in parentheses in front of a value. It asks the compiler to convert the value, and it is required when the conversion can lose information:
double price = 9.99;
int priceInt = (int) price; // 9
Without the cast, int priceInt = price; does not compile, with a message that an explicit conversion exists. The cast truncates: it drops the decimal part and never rounds, so 9.99 becomes 9, not 10. Truncation goes toward zero, so (int) -9.99 is -9. To round instead, use Math.Round first:
Console.WriteLine((int) Math.Round(9.99)); // 10
Going the other way is automatic, because no information is lost. double d = age; compiles and gives 25, without a cast.
String to int: int.Parse
A cast does not work on text. (int) "2024" is a compile error, because a string is not a number in disguise. To read the digits in a string, use int.Parse:
string year = "2024";
int yearInt = int.Parse(year); // 2024
The matching method for decimals is double.Parse. Both throw a FormatException if the text is not a valid number, so int.Parse("abc") and int.Parse("3.5") crash at run time. When the text might be invalid, int.TryParse reports success instead of throwing:
if (int.TryParse("abc", out int value))
{
Console.WriteLine(value);
}
else
{
Console.WriteLine("not a number");
}
This prints not a number. TryParse returns a bool saying whether it worked, and the out variable receives the number when it did. The idea of checking before you trust input comes up again and again.
The Convert class
C# also has a Convert class with methods such as Convert.ToInt32, Convert.ToDouble and Convert.ToString. They accept many source types, and they behave differently from a cast in one important way: Convert.ToInt32(9.99) rounds to 10 instead of truncating. When a value falls exactly halfway, it rounds to the nearest even number, so Convert.ToInt32(2.5) is 2. For the lesson's three conversions, ToString(), the cast and int.Parse are the right tools.
The exercise, step by step
You start with three variables and add three new ones below them.
int age = 25;
double price = 9.99;
string year = "2024";
- The string form of
age. Declarestring ageStrand assignage.ToString(). - The integer form of
price. Declareint priceIntand assign(int) price. The result is 9, because the cast truncates. - The integer form of
year. Declareint yearIntand assignint.Parse(year). The result is 2024.
int age = 25;
double price = 9.99;
string year = "2024";
string ageStr = age.ToString();
int priceInt = (int) price;
int yearInt = int.Parse(year);
Each new variable has a different type from its source, and each conversion tool fits one pair: ToString() for to-text, a cast for number to number, int.Parse for text to number.
Common mistakes
- Expecting the cast to round.
(int) 9.99is 9. - Casting a string. Use
int.Parseinstead. - Parsing invalid text. Use
TryParsefor input you don't control. - Thinking a conversion changes the original.
(int) priceproduces a new value andpricestays 9.99.
Key takeaways
x.ToString()gives the text form of a value.(int) xconverts adoubletointby dropping the decimals.int.Parse(s)reads a whole number from a string, andint.TryParsedoes so safely.