String to Integer

int.TryParse

c# tryparse

int.TryParse method allows us to convert a string representation of a number to its 32-bit integer value.

TryParse(String, Int32) 
string to integer

TryParse method has two parameters, the first parameter is the string that you want to convert and the second parameter is modified with the out keyword. Also a return value indicates whether the TryParse is succeeded.

try
{
	string num = "100";
	int value;
	bool isSuccess = int.TryParse(num, out value);
	if(isSuccess)
	{
		value = value + 1;
		Console.WriteLine("Value is " + value);
	}
}
catch (FormatException e)
{
	Console.WriteLine(e.Message);
}
Output : Value is 101

You can also use Int32.Parse() method to convert string to int

try
{
	int strVal = Int32.Parse("2000");
	strVal = strVal +1;
	Console.WriteLine("Value is " + strVal);
}
catch (FormatException e)
{
    Console.WriteLine(e.Message);
}
Output : Value is 2001

Convert class

c# integer to string

The C# language has a Convert class that allows you to convert a String to an Integer.

try
{
    string  no = "100";
    int  value = Convert.ToInt32(no);
	value = value + 1;
    Console.WriteLine("Value is " + value);
}
catch (FormatException e)
{
    Console.WriteLine(e.Message);
}
Output : Value is 101

String to Number

Following are the Convert functions that convert string to different numerical types.

Converting String to decimal

decimal		ToDecimal(String)

Converting String to float

float		ToSingle(String)

Converting String to double

double		ToDouble(String)

Converting String to short

short		ToInt16(String)

Converting String to long

long		ToInt64(String)
NEXT.....String and System.string









Home   C#   Asp.Net   VB.Net