In C#, it’s very possible that you may find yourself wanting to convert a string to an integer. Let’s say you have a string that contains a number, like “83”, for example, and you want 83 to be represented as an integer, not a string (maybe you want to use it for calculations or store it in a database…there are many different reasons for wanting to convert a string to an integer). There are a few different ways you can go about doing this.
The simplest way is to use the int.Parse method. This is a very simple method that can be used to return an integer. Here’s how you would use it:
string words = "83"; int number = int.Parse("text"); Console.WriteLine(number);
So the output of the example above would be the number 83 (in the form of an integer, not a string, written to the console).
The int.Parse method works great if you’re sure that the conversion from string to an integer is going to be successful and error free. If there are errors, it’ll slow down your code a lot. If for example, you think it’s possible that a string like the one in the example below could try to be converted to an integer, the int.Parse method is not the way to go:
string food = "pizza"; int number = int.Parse("food"); Console.WriteLine(number);
The code in the example above will throw an error, because the string “pizza” doesn’t adhere to the format of an integer.
Another method you can use to convert strings to ints that does a better job of handling errors is by using the int.TryParse method. When you use this method, you can give your code some options for how to handle errors, or strings that don’t aren’t numbers and can’t be converted.
Here’s an example of how you’d use int.TryParse:
string test = "26"; int number; bool res = int.TryParse(test, out number); Console.WriteLine(number);
The output of the code above would be the integer 26 written to the console. But, if we try converting a string of letter characters again (like pizza), instead of getting an error, we would get the integer 0 written to the console. The code for trying to convert that string would look like this:
string test = "pizza"; int number; bool res = int.TryParse(test, out number); Console.WriteLine(number);
If you’re looking to convert a string to an integer, the int.TryParse method is probably the right way to go. It’s much more efficient in handling errors and, for this reason, won’t slow your code down nearly as much as the int.Parse method.