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
situs toto pucuk4d indobet toto slot slot depo 10k 8kuda4d judi bola toto toto toto toto slot bobatoto daftar logototo situs toto situs toto toto bydplay patentoto situs toto slot 4D situs toto leon188 situs toto toto toto situs toto ilmutoto mix parlay bayitoto mawar800 login popotogel prize hongkong malam ini toto joker11 toto slot lingkartoto ilmutoto https://foundvinylrecords.com/ depo 5k panen100 semibola popo togel https://asupantoto.co/ pompa4d slot pascol4d login pascol4d login sbobet88 sbobet88 https://nolimithoki.dev/ ini777 dinasti33 slot situs toto slot88 slot jepang slot depo 5k pucuk4d https://www.juara288.asia/ https://shopjoliboutique.com/ slot 4d RP888 toto toto pascol4d situs toto kari4d flokitoto slot gacor logototo slot depo 5k bobatoto bobatoto bobatoto sontogel PASCOL4D LOGIN mpo slot situs toto slot situs slot pakde4d link slot popotogel login nobu99 logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo bobatoto istanaslot sumbartoto mataramtoto meteorbet88 login rp888 AMANAHTOTO www.pajaktoto.io kari4d kari4d kari4d kari4d pascol4d pascol4d pascol4d situs toto toto slot toto slot SLOT GACOR slot gacor slot bento11 link slot gacor AMANAHTOTO KARI4D PUCUK4D pascol4d situs slot situs slot toto slot titi4d KARI4D DVTOTO PUCUK4D AMANAHTOTO slot gacor toto toto slot slot AMANAHTOTO toto jinhoki AMANAHTOTO toto slot slot777 situs slot situs slot situs slot AMANAHTOTO https://www.asupan188.dev/ slot gacor gampang menang coloktoto coloktoto coloktoto toto slot toto slot gacor bwo303 situs toto toto slot slot gacor slot88 slot gacor slot gacor slot gacor slot gacor situs slot link slot toto toto toto slot gacor slot resmi slot88 situs toto MySlot188 SlotPoker188 slot gacor slot gacor pucuk4d PASCOL4D slot gacor slot gacor situs slot link slot pentaslot SLOT GACOR AMANAHTOTO TOTO 4D pajaktoto slotvip toto togel situs toto toto slot situs slot situs slot situs slot toto slot gacor slot777 toto slot slot gacor situs slot link slot slot thailand
situs toto pucuk4d indobet toto slot slot depo 10k 8kuda4d judi bola toto toto toto toto slot bobatoto daftar logototo situs toto situs toto toto bydplay patentoto situs toto slot 4D situs toto leon188 situs toto toto toto situs toto ilmutoto mix parlay bayitoto mawar800 login popotogel prize hongkong malam ini toto joker11 toto slot lingkartoto ilmutoto https://foundvinylrecords.com/ depo 5k panen100 semibola popo togel https://asupantoto.co/ pompa4d slot pascol4d login pascol4d login sbobet88 sbobet88 https://nolimithoki.dev/ ini777 dinasti33 slot situs toto slot88 slot jepang slot depo 5k pucuk4d https://www.juara288.asia/ https://shopjoliboutique.com/ slot 4d RP888 toto toto pascol4d situs toto kari4d flokitoto slot gacor logototo slot depo 5k bobatoto bobatoto bobatoto sontogel PASCOL4D LOGIN mpo slot situs toto slot situs slot pakde4d link slot popotogel login nobu99 logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo bobatoto istanaslot sumbartoto mataramtoto meteorbet88 login rp888 AMANAHTOTO www.pajaktoto.io kari4d kari4d kari4d kari4d pascol4d pascol4d pascol4d situs toto toto slot toto slot SLOT GACOR slot gacor slot bento11 link slot gacor AMANAHTOTO KARI4D PUCUK4D pascol4d situs slot situs slot toto slot titi4d KARI4D DVTOTO PUCUK4D AMANAHTOTO slot gacor toto toto slot slot AMANAHTOTO toto jinhoki AMANAHTOTO toto slot slot777 situs slot situs slot situs slot AMANAHTOTO https://www.asupan188.dev/ slot gacor gampang menang coloktoto coloktoto coloktoto toto slot toto slot gacor bwo303 situs toto toto slot slot gacor slot88 slot gacor slot gacor slot gacor slot gacor situs slot link slot toto toto toto slot gacor slot resmi slot88 situs toto MySlot188 SlotPoker188 slot gacor slot gacor pucuk4d PASCOL4D slot gacor slot gacor situs slot link slot pentaslot SLOT GACOR AMANAHTOTO TOTO 4D pajaktoto slotvip toto togel situs toto toto slot situs slot situs slot situs slot toto slot gacor slot777 toto slot slot gacor situs slot link slot slot thailand