0Pricing
C# Academy · Lesson

The Convert Class and Parsing

Parse and convert with Convert and TryParse.

Converting Strings to Numbers

User input arrives as text. To compute with it you must convert strings to numbers. C# offers Convert, Parse, and TryParse.

using System;

class Program
{
    static void Main()
    {
        string input = "42";
        int number = int.Parse(input);
        Console.WriteLine(number + 8);
    }
}

int.Parse

int.Parse turns a numeric string into an int. It throws a FormatException if the text is not a valid number.

using System;

class Program
{
    static void Main()
    {
        try
        {
            int n = int.Parse("abc");
            Console.WriteLine(n);
        }
        catch (FormatException)
        {
            Console.WriteLine("Not a valid number");
        }
    }
}

All lessons in this course

  1. Value Types vs Reference Types
  2. Boxing and Unboxing
  3. Implicit and Explicit Conversions
  4. The Convert Class and Parsing
← Back to C# Academy