C#: How to convert string to int in C#

 C#     sbo     Updated on Oct 24, 2014     VIKRAM     791   

Introduction:

In this article i will explain how to convert string to integer in C#. And how many ways we can convert string to integer.

You can convert a string to a integer by using ToInt32(String) method.

Example:

string str = "23";
int a = Convert.ToInt32(str);

Output:

23

Another way of converting a string to an int is through the Parse or TryParse methods of the System.Int32 struct.

Parse Example:

int numVal = Int32.Parse("-105");
Console.WriteLine(numVal);

Output:

-105

Example:

try
{ 
  int m = Int32.Parse("abc"); 
} 
catch (FormatException e)
{ 
  Console.WriteLine(e.Message);
}

Output: 

Input string was not in a correct format.

TryParse Example:

int j; 
bool result = Int32.TryParse("-105", out j);

if (true == result)
{
  Console.WriteLine(j);
}
else
{
  Console.WriteLine("String could not be parsed.");
}

Output:

-105

Note: TryParse returns true if the conversion succeeded and stores the result in the specified variable.  

If you want to assign a default value instead of displaying error message when conversion fails use Ternary Operator along with TryParse.

See the following examples:

Example:

int num; 
int result = Int32.TryParse("-105", out num) ? num : num;

Output:

-105

Example:

int num; 
int result = Int32.TryParse("abc", out num) ? num : num;

Output:

0

In the above example coversion fails. So, default value will be assigned to result.

  Related Articles
SQL Server: Variables
SQL Server: Differences between CHAR, NCHAR, VARCHAR and NVARCHAR
SQL Server: System Databases
SQL Server: Insert values into Identity Column
ASP.Net: List View Basic Example
JQuery: How to replace string in JQuery
Java Script: How to replace string in Java Script
C#: How to replace string in C#
SQL Server: How to replace string in SQL Server
SQL Server: How to get fixed length number format in SQL Server (or) How to prefix zeros to number, to get fixed length number format in SQL Server
  Recent Articles
SQL Server: Variables
SQL Server: Differences between CHAR, NCHAR, VARCHAR and NVARCHAR
SQL Server: System Databases
SQL Server: Insert values into Identity Column
ASP.Net: List View Basic Example
JQuery: How to replace string in JQuery
Java Script: How to replace string in Java Script
C#: How to replace string in C#
SQL Server: How to replace string in SQL Server
SQL Server: How to get fixed length number format in SQL Server (or) How to prefix zeros to number, to get fixed length number format in SQL Server