Different ways to convert String to Integer in C#
Last Updated :
05 Nov, 2024
In C#, we can convert a string to an integer using various methods. This process is common when dealing with user input or data parsing. In this article, we will learn Different ways to convert String to Integer in C#.
Example:
Input String: "10"
Output String: 10
Explanation: The input string "10" is converted to the output integer 10, allowing it to be used in numerical operations.
Syntax
Int32.Parse() # Parse Method
TryParse() # TryParse Method
Convert.ToInt32() # Convert Method
Using the Parse Method
The Int32.Parse() method converts a string representation of a number to its 32-bit signed integer equivalent.
Syntax
int length = Int32.Parse(string);
Example:
C#
using System;
namespace GeeksforGeeks {
class GFG {
public static void Main(string[] args) {
string l = "10";
int length = Int32.Parse(l);
Console.WriteLine("Converted: {0}", length);
}
}
}
Using the TryParse Method
The TryParse() method attempts to convert a string to an integer without throwing an exception if the conversion fails. It returns a boolean indicating success or failure.
Syntax
bool success = Int32.TryParse(string, out int result);
Example:
C#
using System;
namespace GeeksforGeeks {
class GFG {
public static void Main(string[] args) {
string l = "10";
int length;
// Attempt to parse the string
bool success = Int32.TryParse(l, out length);
if (success) {
Console.WriteLine("Converted: {0}", length);
} else {
Console.WriteLine("Failed.");
}
}
}
}
Using the Convert Method
The Convert.ToInt32() method converts a specified value to a 32-bit signed integer. It handles null values gracefully.
Syntax
int length = Convert.ToInt32(string);
C#
using System;
namespace GeeksforGeeks {
class GFG {
public static void Main(string[] args) {
string l = "10";
int length = Convert.ToInt32(l);
Console.WriteLine("Converted: {0}", length);
}
}
}
Conclusion
In C#, converting a string to an integer can be done using the Parse, TryParse, or Convert.ToInt32 methods. Each method has its use case and handling for various input scenarios, allowing developers to choose the most appropriate one for their needs.
Explore
Introduction
Fundamentals
Control Statements
OOP Concepts
Methods
Arrays
ArrayList
String
Tuple
Indexers