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 toto slot toto togel indobet situs toto toto slot toto slot toto slot toto slot depo 10k 8kuda4d toto judi bola 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 situs toto situs toto ilmutoto toto mix parlay bayitoto toto toto toto toto ilmutoto toto toto mawar800 login popotogel prize hongkong malam ini toto joker11 toto slot pucuk4d lingkartoto Pucuk4D Login UGSLOT slot gacor ilmutoto https://foundvinylrecords.com/ depo 5k slot gacor panen100 semibola MySlot188 monk4d popo togel tikus4d https://asupantoto.co/ pompa4d Pakde4D lingkartoto AMANAHTOTO efekjitu slot pascol4d login pascol4d login sbobet88 sbobet88 https://nolimithoki.dev/ ini777 benteng786 dinasti33 slot slot gacor kaskustoto situs toto slot88 slot gacor slot jepang slot depo 5k pucuk4d patentoto https://www.juara288.asia/ flokitoto https://www.aishe-j.org/ barges88 mataramtoto https://shopjoliboutique.com/ apo388 slot 4d RP888 toto toto toto toto toto slot gacor toto pascol4d situs toto kari4d flokitoto slot gacor logototo slot depo 5k bobatoto bobatoto bobatoto slot gacor sontogel PASCOL4D LOGIN mpo slot sumbartoto mataramtoto slot gacor situs toto slot situs slot situs toto pakde4d link slot sumbartoto Login bandar toto mataramtoto popotogel login slot gacor nobu99 situs toto logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo Slot Malaysia bobatoto istanaslot sumbartoto mataramtoto meteorbet88 login 33ag
togel slot situs toto pucuk4d agb99 toto slot toto togel indobet situs toto toto slot toto slot toto slot toto slot depo 10k 8kuda4d toto judi bola 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 situs toto situs toto ilmutoto toto mix parlay bayitoto toto toto toto toto ilmutoto toto toto mawar800 login popotogel prize hongkong malam ini toto joker11 toto slot pucuk4d lingkartoto Pucuk4D Login UGSLOT slot gacor ilmutoto https://foundvinylrecords.com/ depo 5k slot gacor panen100 semibola MySlot188 monk4d popo togel tikus4d https://asupantoto.co/ pompa4d Pakde4D lingkartoto AMANAHTOTO efekjitu slot pascol4d login pascol4d login sbobet88 sbobet88 https://nolimithoki.dev/ ini777 benteng786 dinasti33 slot slot gacor kaskustoto situs toto slot88 slot gacor slot jepang slot depo 5k pucuk4d patentoto https://www.juara288.asia/ flokitoto https://www.aishe-j.org/ barges88 mataramtoto https://shopjoliboutique.com/ apo388 slot 4d RP888 toto toto toto toto toto slot gacor toto pascol4d situs toto kari4d flokitoto slot gacor logototo slot depo 5k bobatoto bobatoto bobatoto slot gacor sontogel PASCOL4D LOGIN mpo slot sumbartoto mataramtoto slot gacor situs toto slot situs slot situs toto pakde4d link slot sumbartoto Login bandar toto mataramtoto popotogel login slot gacor nobu99 situs toto logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo logototo Slot Malaysia bobatoto istanaslot sumbartoto mataramtoto meteorbet88 login 33ag