Start learning free

LESSON 14 OF 347 · VARIABLES

Type Conversion in C#: ToString, Casts and int.Parse

Lesson Read the full explanation

In Java, every value has a type: int, double, String, and so on. Sometimes you need to convert a value from one type to another.

Common type conversion methods:

String.valueOf(x)       // converts int or double → String
Integer.parseInt(s)     // converts String → int
Double.parseDouble(s)   // converts String → double
(int) x                 // casts double → int (drops decimal)

Here are some examples:

int score = 42;
String scoreStr = String.valueOf(score);    // "42"

double weight = 70.8;
int weightInt = (int) weight;               // 70  (decimal dropped)

String count = "100";
int countInt = Integer.parseInt(count);     // 100

Note that casting a double to int with (int) simply drops the decimal - it does not round.


Assignment
Follow the Coding Tutorial and convert each variable to a different type!


Hint
Use String.valueOf(), (int) casting, and Integer.parseInt().

STEP 1 OF 3
    Ctrl + Enter to check

    C# · VARIABLES

    Type Conversion in C#, explained

    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";
    
    1. The string form of age. Declare string ageStr and assign age.ToString().
    2. The integer form of price. Declare int priceInt and assign (int) price. The result is 9, because the cast truncates.
    3. The integer form of year. Declare int yearInt and assign int.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.99 is 9.
    • Casting a string. Use int.Parse instead.
    • Parsing invalid text. Use TryParse for input you don't control.
    • Thinking a conversion changes the original. (int) price produces a new value and price stays 9.99.

    Key takeaways

    • x.ToString() gives the text form of a value.
    • (int) x converts a double to int by dropping the decimals.
    • int.Parse(s) reads a whole number from a string, and int.TryParse does so safely.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free