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
indobet toto slot toto toto bobatoto daftar logototo patentoto situs toto slot 4D toto bayitoto popotogel prize hongkong malam ini joker11 lingkartoto depo 5k panen100 semibola slot sbobet88 sbobet88 https://nolimithoki.dev/ dinasti33 slot slot jepang https://www.juara288.asia/ slot 4d toto toto situs toto flokitoto slot gacor logototo slot depo 5k bobatoto bobatoto bobatoto sontogel mpo slot situs toto slot situs slot bobatoto kari4d kari4d kari4d kari4d pascol4d pascol4d pascol4d slot gacor bento11 link slot gacor toto toto slot toto situs slot situs slot situs slot https://www.asupan188.dev/ slot gacor gampang menang toto slot gacor bwo303 situs toto toto slot slot gacor slot88 slot gacor situs slot link slot slot gacor pucuk4d PASCOL4D situs slot link slot pajaktoto slotvip situs toto toto slot situs slot situs slot situs slot toto slot gacor slot777 situs slot link slot situs judi bola POPOTOGEL : Situs Resmi Bandar Toto Togel Macau dengan Prediksi Gokil Pasti Akurat link slot slot gacor situs slot slot gacor slot gacor situs slot link slot gacor Slot88 Slot88 slot gacor situs toto toto slot pulsa slot777 link slot gacor situs gacor slot gacor leon188 slot gacor bandarqq slot gacor slot gacor Slot88 slot gacor Slot88 situs slot slot gacor poker online slot88 Slot88 slot gacor slot terbaru slot gacor situs gacor situs slot slot gacor situs slot Situs Slot POPOTOGEL: Regulasi Bandar Situs Togel Resmi & Bola Mix Parlay Asia Terpercaya StreamEast Jpmania slot resmi slot slot resmi slot bayitoto patentoto link gacor slot gacor kari4d slot demo slot gacor AMANAHTOTO slot gacor slot gacor StreamEast AMANAHTOTO pascol4d kari4d AMANAHTOTO kari4d bragatoto dokter88 slot gacor slot game patentoto pucuk4d rokokbet rokokbet kari4d pascol4d LOGIN PASCOL4D pucuk4d roma77 judi bola slot depo 10k mpo slot Girang4d
indobet toto slot toto toto bobatoto daftar logototo patentoto situs toto slot 4D toto bayitoto popotogel prize hongkong malam ini joker11 lingkartoto depo 5k panen100 semibola slot sbobet88 sbobet88 https://nolimithoki.dev/ dinasti33 slot slot jepang https://www.juara288.asia/ slot 4d toto toto situs toto flokitoto slot gacor logototo slot depo 5k bobatoto bobatoto bobatoto sontogel mpo slot situs toto slot situs slot bobatoto kari4d kari4d kari4d kari4d pascol4d pascol4d pascol4d slot gacor bento11 link slot gacor toto toto slot toto situs slot situs slot situs slot https://www.asupan188.dev/ slot gacor gampang menang toto slot gacor bwo303 situs toto toto slot slot gacor slot88 slot gacor situs slot link slot slot gacor pucuk4d PASCOL4D situs slot link slot pajaktoto slotvip situs toto toto slot situs slot situs slot situs slot toto slot gacor slot777 situs slot link slot situs judi bola POPOTOGEL : Situs Resmi Bandar Toto Togel Macau dengan Prediksi Gokil Pasti Akurat link slot slot gacor situs slot slot gacor slot gacor situs slot link slot gacor Slot88 Slot88 slot gacor situs toto toto slot pulsa slot777 link slot gacor situs gacor slot gacor leon188 slot gacor bandarqq slot gacor slot gacor Slot88 slot gacor Slot88 situs slot slot gacor poker online slot88 Slot88 slot gacor slot terbaru slot gacor situs gacor situs slot slot gacor situs slot Situs Slot POPOTOGEL: Regulasi Bandar Situs Togel Resmi & Bola Mix Parlay Asia Terpercaya StreamEast Jpmania slot resmi slot slot resmi slot bayitoto patentoto link gacor slot gacor kari4d slot demo slot gacor AMANAHTOTO slot gacor slot gacor StreamEast AMANAHTOTO pascol4d kari4d AMANAHTOTO kari4d bragatoto dokter88 slot gacor slot game patentoto pucuk4d rokokbet rokokbet kari4d pascol4d LOGIN PASCOL4D pucuk4d roma77 judi bola slot depo 10k mpo slot Girang4d