Number Parsing in C#

Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in C#.

using System;

class NumberParsing
{
    static void Main()
    {
        // With float.Parse, we don't need to specify precision
        // as C# floats are always 32-bit and doubles are 64-bit
        float f = float.Parse("1.234");
        Console.WriteLine(f);

        // For int.Parse, we don't need to specify the base or bit size
        // as it's inferred from the method (32-bit) or can be specified by using long.Parse (64-bit)
        int i = int.Parse("123");
        Console.WriteLine(i);

        // To parse hexadecimal numbers, we use the Convert class
        int d = Convert.ToInt32("1c8", 16);
        Console.WriteLine(d);

        // For unsigned integers, we use uint.Parse
        uint u = uint.Parse("789");
        Console.WriteLine(u);

        // C# doesn't have a direct equivalent to Atoi, but int.Parse serves the same purpose
        int k = int.Parse("135");
        Console.WriteLine(k);

        // Parse methods throw an exception on bad input
        try
        {
            int badNumber = int.Parse("wat");
        }
        catch (FormatException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

To run the program, compile it and then execute the resulting executable:

$ csc NumberParsing.cs
$ mono NumberParsing.exe
1.234
123
456
789
135
Input string was not in a correct format.

In C#, the System namespace provides number parsing functionality. Unlike Go’s strconv package, C# uses methods on the respective numeric types (int.Parse, float.Parse, etc.) or the Convert class for more specific conversions.

C# doesn’t require specifying the bit size for parsing as it’s implicit in the method used (e.g., int.Parse for 32-bit integers, long.Parse for 64-bit integers).

For parsing hexadecimal numbers, C# uses the Convert.ToInt32 method with a base parameter, rather than inferring it from the string format.

Error handling in C# typically uses exceptions rather than returning error values. The try-catch block demonstrates how to handle parsing errors.

Next, we’ll look at another common parsing task: URLs.