Retrace will reach End of Life on March 31, 2027. Click here to learn more.

How to Convert C# String to Int

By: mwatson
  |  April 16, 2017

The .NET Framework provides a couple built in ways to convert a C# string to int, or several other numeric datatypes. It is important that you do so in a way that does not throw potential exceptions.

Unsafe Ways to Convert a C# String to Int

You can use a couple built in methods, as shown below, to convert a string to int. Both of these would throw an exception if the string value is not a valid integer.

int.Parse((string) null); // throws exception
int.Parse("Hello"); // throws exception
int.Parse("1.5"); // throws exception
var i = int.Parse("1"); // Works!

var i2 = Convert.ToInt32((string) null); //No exception! returns 0
Convert.ToInt32("hello"); //throws exception
Convert.ToInt32("1.5"); //throws exception
Convert.ToInt32("1"); // Works!

The built-in methods Convert.ToInt32() and int.Parse() produce the same results, except for the null string scenario. If we peek under the covers to see what the source code for Convert.ToInt32() does, you can see it has special logic to look for null and calls int.Parse internally.

public static int ToInt32(string value)
{
    if (value == null)
       return 0;
    return int.Parse(value, (IFormatProvider) CultureInfo.CurrentCulture);
}

How to Prevent Exceptions When Converting a C# String to Int

Bad data is inevitable. You should definitely handle potential exceptions when parsing data and converting datatypes. In this example, possible exceptions converting a string to int.

Luckily, the .NET Framework provides int.TryParse which is designed for this exact problem. Below is an example of how to properly use it.

string incomingData = "Hello";
int parsedResult; 
int.TryParse(incomingData, out parsedResult);

The only problem is that the variable parsedResult will end up being a 0 if the TryParse fails. The data being parsed could also be a 0. If you need to know the difference between the incomingData being 0 and just defaulting to 0, you will need to actually use the boolean result of TryParse to know if it actually parsed or not.

string incomingData = "Hello";
int parsedResult; 

if (int.TryParse(incomingData, out parsedResult))
{
   //do something with the data. 
}

Try Stackify’s free code profiler, Prefix, to write better code on your workstation. Prefix works with .NET, Java, PHP, Node.js, Ruby, and Python.

Make Some Helper Methods to Simplify Converting a C# String to Int

A good way to simplify your TryParse code is to make your own helper methods via C# extension methods. You could make extension methods to support different default values or nullable integers.

public static class IntegerExtensions
{
    public static int ParseInt(this string value, int defaultIntValue = 0)
    {
        int parsedInt;
        if (int.TryParse(value, out parsedInt))
        {
            return parsedInt;
        }

        return defaultIntValue;
    }

    public static int? ParseNullableInt(this string value)
    {
        if (string.IsNullOrEmpty(value))
            return null;

        return value.ParseInt();
    }
}

You could then use these helper methods in your code to work with a default other than 0, or a nullable integer.

int number = myString.ParseInt(); // returns value or 0
int number2 = myString2.ParseInt(-1); // with default value -1
int? number3 = myString3.ParseNullableInt(); // returns value or null

Conclusion

Converting a string to int is a common task that developers do almost daily. This guide should help you avoid exceptions in your code! Check out our guide on C# exception handling best practices to learn more about exception handling.

Improve Your Code with Retrace APM

Stackify's APM tools are used by thousands of .NET, Java, PHP, Node.js, Python, & Ruby developers all over the world.
Explore Retrace's product features to learn more.

Learn More
togel slot situs toto pucuk4d agb99 togel toto slot toto togel toto slot indobet situs toto toto slot toto slot toto slot toto toto situs toto toto slot slot depo 10k toto togel 8kuda4d toto judi bola kenangan4d toto situs toto toto toto toto situs toto toto toto slot bobatoto daftar situs toto logototo situs toto situs toto toto bydplay patentoto situs toto slot 4D situs toto leon188 situs toto slot gacor terbaru toto toto slot toto situs toto situs toto MORFINTOTO ilmutoto toto mix parlay bayitoto toto toto toto toto ilmutoto toto toto mawar800 login popotogel prize hongkong malam ini toto slot gacor joker11 toto slot pucuk4d lingkartoto lingkartoto Pucuk4D Login PREMANTOTO UGSLOT slot gacor slot gacor slot gacor AMANAHTOTO toto lingkartoto lingkartoto toto situs toto ilmutoto toto slot gacor rp888 https://foundvinylrecords.com/ depo 5k slot gacor toto slot gacor toto mataramtoto toto panen100 semibola slot gacor Pakde4D situs gacor MySlot188 SlotPoker188 toto togel 77ag monk4d popo togel tikus4d https://asupantoto.co/ Login Batak5D pompa4d lingkartoto