Table of contents >> Introduction > Converting numbers from String
High importance article

Today, we're focusing on converting strings to numbers, a common task you'll encounter in programming. In C#, we often need to convert string data into numbers, in order to perform calculations or data manipulation, and most of the times that data will come from users entering it in graphical user interfaces that collect data usually as string. A TextBox gets the text entered by user as string, even if that text represents a number. The same thing is true for the console programs, we've already used Console.ReadLine() to get data from users. So, coming as string, we still need to convert that data to numbers sometimes, and it's not as easy as the other conversions we've seen before (implicit and explicit). Let's look at a few ways to do this and when you might use each one.

Parse function:

This function is straightforward, but be careful: if the string can't be converted, it will throw an exception of which we will learn in the future, but just know that it is a special kind of error that, when left unhandled in a special construct called a try-catch block, can crash your program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
 
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            string ageText = "57";
            
            try
            {
                int ageNumeric = int.Parse(ageText);
                Console.WriteLine(ageNumeric);
            }
            catch (FormatException)
            {
                Console.WriteLine("Invalid number!");
            }
            
            Console.ReadLine();
        }
    }
}

The above example works, because the text "57" can be converted to the number 57. However, this throws an exception that will be caught by the catch block, which will display an error message:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
 
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            string ageText = "fifty seven";
            
            try
            {
                int ageNumeric = int.Parse(ageText);
                Console.WriteLine(ageNumeric);
            }
            catch (FormatException)
            {
                Console.WriteLine("Invalid number!");
            }
            
            Console.ReadLine();
        }
    }
}

This happens because although for us, humans, those words mean a number, for the compiler they don't, for what it cares, it could be a romance novel. Just imagine: if I were to write that text as "fifty-seven", would that textual representation of a number change in your mind? No, of course not, your brain is able to understand that the dash can be ignored. The compiler cannot take that kind of decissions, therefor, if the text is not the exact identical representation of a number, it cannot be converted to that number, end of debate.

Because the Parse() function can be used on an int, in order to convert the string to an int, that also means that we can call it on other numeric data types, when we want to convert text into those numeric data types: decimal.Parse(), double.Parse(), byte.Parse(), etc. The compiler will also throw an exception when the text is a correct number representation, but outside the allowed range of each numeric data type.

TryParse function:

This function also converts strings to numbers, but instead of throwing an exception when it fails, it returns a boolean value, indicating whether the conversion was successful or not. It looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System;
 
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            string ageText = "57";
            
            bool conversionResult = int.TryParse(ageText, out int ageNumeric);
            
            Console.ReadLine();
        }
    }
}

I know we haven't talked about out parameters yet, but do not concern yourself with this yet. You only need to undestand this: the function TryParse() returns a boolean result that indicates if the conversion succeeded or not, but we also need the converted value itself, and since there is no easy way to return multiple things from a function, we get the converted number as an out parameter, which we can then use as if we declared a normal variable.

We will learn in a few lessons that because TryParse() returns a boolean result, we can use that result inside conditional statements, something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;
 
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            string ageText = "57";
            
            if (int.TryParse(ageText, out int ageNumeric))
            {
                Console.WriteLine(ageNumeric);
            }
            else
            {
                Console.WriteLine("Invalid number!");
            }
            
            Console.ReadLine();
        }
    }
}

Convert class:

The Convert class contains a lot of functions for converting between data types, some of which are suitable for converting strings into numeric types. We can use it like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
 
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            string ageText = "57";
            
            try
            {
                int ageNumeric = Convert.ToInt32(ageText);
                Console.WriteLine(ageNumeric);
            }
            catch (FormatException)
            {
                Console.WriteLine("Invalid number!");
            }
            
            Console.ReadLine();
        }
    }
}

You probably noticed that its usage is identical to the Parse() function, but there is one difference between the way they handle the conversions: Convert.ToInt32() will also convert strings that have a null value, returning 0.

If you've noticed that the function is using the alias of the data type, and not its keyword, good job. This means that if we wanted to convert to a long, we'd have to use Convert.ToInt64(), and so on. Just like the parsing functions that can be used on multiple numeric data types, we also have functions for converting to multiple numeric data types: Convert.ToDecimal(), Convert.ToSingle(), Convert.ToDouble(), and so on.

As beginners, I recommend you take the safer route and use TryParse() function, at least until we will learn about exceptions, and how we can properly deal with them.