In C#, We can easily convert a string to an integer in multiple ways as mentioned below,
- Using
Int32.Parse()
method - Using
Int32.TryParse()
method - Using
Convert.ToInt32()
method
Using Int32.Parse()
method
Int32.Parse()
method is used to convert a string to an integer in C#. We will use Int32
or int
to parse the string.
using System;
namespace ConvertStringToInt
{
class Program
{
public static void Main()
{
string Numstr = "75";
// Parse() method is used to convert a string to an integer
int num = Int32.Parse(Numstr);
// OR
//int num = int.Parse(Numstr);
Console.WriteLine(num);
Console.ReadKey();
}
}
}
Output:
75
If in case of conversion failure, the Parse method will return FormatException
. We will use try...catch
block to handle this exception.
using System;
namespace ConvertStringToInt
{
class Program
{
public static void Main()
{
string Numstr = "75abc"; // Invalid input
try
{
int num = Int32.Parse(Numstr);
Console.WriteLine(num);
}
catch (FormatException)
{
Console.WriteLine("Invalid input");
}
Console.ReadKey();
}
}
}
Output:
Invalid input
Using Int32.TryParse()
method
Int32.TryParse()
method is used to convert a string into an integer. If the conversion is successful then it returns true otherwise returns false.
using System;
namespace ConvertStringToInt
{
class Program
{
public static void Main()
{
string Numstr = "75";
// This method returns true if success
bool success = Int32.TryParse(Numstr, out int num);
// OR
//bool success = int.TryParse(Numstr, out int num);
if (success)
Console.WriteLine(num);
else
Console.WriteLine("Invalid input.");
Console.ReadKey();
}
}
}
Output:
75
Using Convert.ToInt32()
method
Convert.ToInt32()
method is also doing the same job as the above methods do as shown below,
using System;
namespace ConvertStringToInt
{
class Program
{
public static void Main()
{
string NumStr = "101";
// ToInt32 method converts a string to an integer
int num = Convert.ToInt32(NumStr);
Console.WriteLine(num);
Console.ReadKey();
}
}
}
Output:
101
If the conversion fails, the ToInt32
method returns the FormatException. We will use try..catch
block to handle the exception.
Comments (0)