[c#] How to convert string to integer in C#

How do I convert a string to an integer in C#?

This question is related to c# .net string int type-conversion

The answer is


int myInt = System.Convert.ToInt32(myString);

As several others have mentioned, you can also use int.Parse() and int.TryParse().

If you're certain that the string will always be an int:

int myInt = int.Parse(myString);

If you'd like to check whether string is really an int first:

int myInt;
bool isValid = int.TryParse(myString, out myInt); // the out keyword allows the method to essentially "return" a second value
if (isValid)
{
    int plusOne = myInt + 1;
}

4 techniques are benchmarked here.

The fastest way turned out to be the following:

y = 0;
for (int i = 0; i < s.Length; i++)
       y = y * 10 + (s[i] - '0');

"s" is your string that you want converted to an int. This code assumes you won't have any exceptions during the conversion. So if you know your string data will always be some sort of int value, the above code is the best way to go for pure speed.

At the end, "y" will have your int value.


If you are sure that you have "real" number in your string, or you are comfortable of any exception that might arise, use this.

string s="4";
int a=int.Parse(s);

For some more control over the process, use

string s="maybe 4";
int a;
if (int.TryParse(s, out a)) {
    // it's int;
}
else {
    // it's no int, and there's no exception;
}

string varString = "15";
int i = int.Parse(varString);

or

int varI;
string varString = "15";
int.TryParse(varString, out varI);

int.TryParse is safer since if you put something else in varString (for example "fsfdsfs") you would get an exception. By using int.TryParse when string can't be converted into int it will return 0.


You can use either,

    int i = Convert.ToInt32(myString);

or

    int i =int.Parse(myString);

int a = int.Parse(myString);

or better yet, look into int.TryParse(string)


If you're sure it'll parse correctly, use

int.Parse(string)

If you're not, use

int i;
bool success = int.TryParse(string, out i);

Caution! In the case below, i will equal 0, not 10 after the TryParse.

int i = 10;
bool failure = int.TryParse("asdf", out i);

This is because TryParse uses an out parameter, not a ref parameter.


int i;

string result = Something;

i = Convert.ToInt32(result);

int i;
string whatever;

//Best since no exception raised
int.TryParse(whatever, out i);

//Better use try catch on this one
i = Convert.ToInt32(whatever);

class MyMath
{
    public dynamic Sum(dynamic x, dynamic y)
    {
        return (x+y);
    }
}

class Demo
{
    static void Main(string[] args)
    {
        MyMath d = new MyMath();
        Console.WriteLine(d.Sum(23.2, 32.2));
    }
}

Do something like:

var result = Int32.Parse(str);

bool result = Int32.TryParse(someString, out someNumeric)

This method will try to convert someString into someNumeric, and return a result depends if the conversion is successful, true if conversion is successful and false if conversion failed. Take note that this method will not throw exception if the conversion failed like how Int32.Parse method did and instead it returns zero for someNumeric.

For more information, you can read here:

https://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
&
How to convert string to integer in C#


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to int

How can I convert a char to int in Java? How to take the nth digit of a number in python "OverflowError: Python int too large to convert to C long" on windows but not mac Pandas: Subtracting two date columns and the result being an integer Convert bytes to int? How to round a Double to the nearest Int in swift? Leading zeros for Int in Swift C convert floating point to int Convert Int to String in Swift Converting String to Int with Swift

Examples related to type-conversion

How can I convert a char to int in Java? pandas dataframe convert column type to string or categorical How to convert an Object {} to an Array [] of key-value pairs in JavaScript convert string to number node.js Ruby: How to convert a string to boolean Convert bytes to int? Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe SQL Server: Error converting data type nvarchar to numeric How do I convert a Python 3 byte-string variable into a regular string? Leading zeros for Int in Swift