[c#] How the int.TryParse actually works

I've looked for int.TryParse method implementation, how does it work actually, but I haven't found. I have to know, about a string, whether it's a numeric value, but I don't want to convert it at the this time.

So I need only the bool result from int.TryParse. So the questions are:

  1. Is there any function which can provide only the bool result,

and

  1. I'd like to know, how the int.TryParse actually works (is there a try ... catch inside or iterates through the characters of input string)?

This question is related to c#

The answer is


Regex is compiled so for speed create it once and reuse it.
The new takes longer than the IsMatch.
This only checks for all digits.
It does not check for range.
If you need to test range then TryParse is the way to go.

private static Regex regexInt = new Regex("^\\d+$");
static bool CheckReg(string value)
{
    return regexInt.IsMatch(value);
}

TryParse is the best way for parse or validate in single line:

int nNumber = int.TryParse("InputString", out nNumber) ? nNumber : 1;

Short description:

  1. nNumber will initialize with zero,
  2. int.TryParse() try parse "InputString" and validate it, if succeed set into nNumber.
  3. short if ?: checking int.TryParse() result, that return nNumber or 1 as default value.

We can now in C# 7.0 and above write this:

if (int.TryParse(inputString, out _))
{
    //do stuff
}

Just because int.TryParse gives you the value doesn't mean you need to keep it; you can quite happily do this:

int temp;
if (int.TryParse(inputString, out temp))
{
    // do stuff
}

You can ignore temp entirely if you don't need it. If you do need it, then hey, it's waiting for you when you want it.

As for the internals, as far as I remember it attempts to read the raw bytes of the string as an int and tests whether the result is valid, or something; it's not as simple as iterating through looking for non-numeric characters.


Check this simple program to understand int.TryParse

 class Program
 {
    static void Main()
    {
        string str = "7788";
        int num1;
        bool n = int.TryParse(str, out num1);
        Console.WriteLine(num1);
        Console.ReadLine();
    }
}

Output is : 7788