Site Search
Homepage of Otaku No Zoku
Complete Archives of Otaku No Zoku
About Otaku No Zoku
Subscribe to Otaku No Zoku
Bookmark Otaku No Zoku

C# How To Convert String To Integer Value :

Need to convert a string in to an int in C#? That sort of task is trivial thanks to the TryParse method of the System.Int32 structure which is a standard part of the .NET Framework. TryParse does exactly what you need by taking a properly formatted string and converting it to an integer.

0113The great thing about the built-in functionality is that you do not need to concern yourself with handling whitespace or the optional plus or minus sign in front of the number.

Back in the day, we had to wring the oil from the dinosaurs to run the generators before we could switch on the computers before we could even begin to write a function to handle this kind of conversion.

That’s how primitive it was in the early 1980’s!

The TryParse function works by taking two parameters, the first parameter is a string representation of an integer number, meaning only digts and an optional sign — the function ignores any whitespace at the beginning or end of the string — and the second is an output only parameter, indicated by using the out modifier keyword, to hold the result of the conversion. The function also returns a Boolean value indicating success (true) or failure (false).

Scroll down towards the bottom of the page for just the source code, or read on for how to use the function.

Int32.TryParse Method Definition

public static bool TryParse(string s, out int result)

Parameters

Parameter Type Description
s System.String String containing the number to convert.
result System.Int32 A 32-bit signed integer equivalent to the number contained in System.String s parameter if the conversion succeeded. Contains zero if the conversion failed for any reason.

Return Value

Type Description
System.Boolean Returns Boolean true on a succcessful conversion, false otherwise.

The conversion of the System.String s parameter to a System.In32 integer will fail if the s parameter is null or not formatted as a valid integer. The conversion will also fail if the string representation of the number is less than System.Int32.MinValue, which is -2,147,483,648, or System.Int32.MaxValue, which is 2,147,483,647.

The System.Int32 result parameter, because it is an out (output only) parameter, does not need to be initialised before being passed to the function.

The TryParse method is similar to the Parse method of the System.Int32 structure except that the functionalty inside of TryParse is wrapped in a try/catch exception handler so that any errors in the conversion process are handled inside of the function. This means you do not have to deal with errors that would throw an exception. Most of the time, TryParse is the function you need to do the heavy lifting for you, the Parse method only being used when you want to know about the type of the exception and why the number could not be converted.

The System.String s parameter is formatted so:

[ws][sign]digits[ws]

Where:

Element Description
ws Optional white space which will be ignored.
sign An optional positive or negative sign.
digits One or more digits in the range 0 to 9.

As you can see in the formatting table, any whistepace is ignored and the TryParse method only works on normal decimal digits. To convert a hexadecimal string, the slightly more convoluted Int32.TryParse(String, NumberStyles, IFormatProvider, Int32) needs to be used.

Converting A String To An Integer Value

This program demonstrates how to convert a numeric value that is held in a string, to an integer value, using the TryParse functionality of the System.Integer class.

The Steps

Enumerate the steps that the program will go through to solve the problem

  1. Declare a string variable with a value that represents a valid integer.
  2. Attempt to parse the value using the TryParse functionality of the integer type.
  3. Print out a message if the converted value is above the required level for the meme to activate.

The Source Code

using System;

class ConvertStringToInt
{
  static void Main()
  {
    // declare a string variable with a value that represents a valid integer
    string sillyMeme = "9001";

    int memeValue;
    // attempt to parse the value using the TryParse functionality of the integer type
    int.TryParse(sillyMeme, out memeValue);

    // print out a message if the converted value is above the required level fo the meme to activate
    if (memeValue > 9000)
    {
      Console.WriteLine(String.Format("It's over 9000! ({0} to be exact.)", memeValue));
    }

  }

}

Program Output

It's over 9000! (9001 to be exact.)

Results

The program output shows that the integer contained in the sillyMeme string was indeed converted correctly. It could easily be made to fail by changing the sillyMeme string to contain an incorrectly formatted integer number, "900+1", for instance.

Summary

All of the intrinsic data types, int, long, string, and so on, and their companion data structures, Int32, Int64, String, contain a robust number of functions for converting between different formats. There are many ways, of course, of converting numbers held in strings but for the most part, TryParse or Parse will be the workhorse functions you use for performing the conversions in almost all cases, be it integer or floating-point, or even Boolean, to the actual data type itself.

Liked This Post?

Subscribe to the RSS feed or follow me on Twitter to stay up to date!