How to convert string into int
in C#?
How to convert string into int
in C#?
Student
Skilled in SEO, content writing, and digital marketing. Completed several years of working in many organizations including multinational companies. I love to learn new things in life that keep me motivated.
Convert string to int in C#
Converting a string to an integer in C# can be done in many ways depending on the specific needs of your application. Here are general ways to do this.
Using int.Parse
The int.Parse method is used to convert a string to an integer. Throw a FormatException if the string is not a valid integer.
Syntax-
using int.TryParse
The int.TryParse method attempts to convert a string to an integer and returns a boolean indicating whether the conversion was successful or not. This method is safe because it does not throw an exception if the conversion fails.
Syntax-
Using Convert.ToInt32
The Convert.ToInt32 method converts the specified string position of any number to a 32-bit equivalent signed integer. It handles null values by returning 0 and throws a FormatException if the string is not a valid integer.
Syntax-
Handling exceptions and edge cases
When using int.Parse or Convert.ToInt32, you must deal with potential exceptions to avoid runtime errors.
Syntax-
int.tryParsebecause it returns the boolean value true or false.Example-
The below example illustrate the different way to convert string into int in C#
Output-
Also, Read: What is Boxing and Unboxing in C#?