C#Dot Net Perls

C#
int.Parse Converts String to int

by Sam Allen

Problem

Parse integers that are stored as sequences of characters in strings, and get their numeric value. Not only that, but we need to know the details and what the best practices for doing this sort of thing are. Here are some input and the output we want to receive.

Input string Output value
"500" 500
"-5" -5
"xyz" null
"0.5" null

C# Solution

There are at least three different ways of parsing ints in C#. There is probably no more important part of programming than knowing how to use these sorts of methods in the framework, but some details can be hard to recall instantly. The following sections discuss the advantages and drawbacks.

Convert.ToInt32 details

This method, along with its siblings Convert.ToInt16 and Convert.ToInt64, is actually a static wrapper method for the int.Parse method I describe below. Therefore it can be slower than int.Parse if the surrounding code is equivalent.

{
    // Convert 'text' string to an integer with Convert.ToInt32.
    // Result will be 500.
    string text = "500";
    int num = Convert.ToInt32(text);
}

int.TryParse details

This is another wrapper around int.Parse. The difference here is that TryParse has its own internal exception handling. Your code that calls this method can simply check the return value. This is fastest when you need to deal with invalid input commonly, and a lot of exceptions would be thrown with the other methods.

{
    // See if we can parse the 'text' string. If we can't, TryParse
    // will return false. Note the "out" keyword in TryParse.
    string text = "500";
    int num;
    bool res = int.TryParse(text, out num);
    if (res == false)
    {
        // String is not a number!
        num = 0;
    }
}

int.Parse details

int.Parse is the simplest method, and is also my favorite for many situations. It throws exceptions on invalid input, which can be slow if they are common. It is faster on valid input than Convert.ToInt32 because it is does not contain any internal null checks. Let's look at the code--it looks good to me.

{
    // Convert string to number. Result will be 500 here.
    string text = "500";
    int num = int.Parse(text);
}

Which method should I use?

My recommendation is to use int.Parse when your input will be valid, as it makes for simpler calling code. It isn't always perfect, but it is a winner. On the other hand, use int.TryParse when you will be dealing with corrupt data. Let me show that in another way.

If your string input Then use
contains lots of non-numeric or invalid characters int.TryParse
is valid and all numeric int.Parse
is guaranteed to be valid an unsafe method if performance is critical

Conclusion

Before frameworks were widely used, programmers would write their own integer conversion routines, but imagine how complex having all those functions could get! You are using the .NET framework now, so you have much more power. If we can master the building blocks (fundamentals) of .NET, we will be able to really use the framework to do amazing things.

Dot Net Perls is dedicated to sharing code and knowledge. It has
© 2007-2008 Sam Allen. All rights reserved.

Ads by The Lounge