-1
        public static void Main()
    {
        int n;
        //n++;    Of course it would cause 'Use of unassigned local variable error' compiler error.
        int.TryParse("not an int", out n);    //not assignig here
        n++;   //now legal. Why?
        System.Console.WriteLine(n);   //1
    }

I can't understand why this code behave like that. In the beginning it doesn't allow to use unassigned variable but after TryParse it does, though TryParse don't assign anything to variable. At some point variable is assigned to default value 0 (I suppose from start) but what is the logic and explanation of such behavior?

Dork
  • 1,816
  • 9
  • 29
  • 57
  • 7
    you know when method has `out` parameter then it HAVE TO assign something? ... so after `SomeMethod(out n)` - `n` is always assigned... and *TryParse don't assign anything to variable* is not a true – Selvin Jun 05 '20 at 10:21
  • 2
    [out](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier) parameter modifier. – Guru Stron Jun 05 '20 at 10:25

2 Answers2

1

Decompiled C# int.TryParse definition:

public static bool TryParse(string s, out int result)
{
    return Number.TryParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}


// System.Number
internal unsafe static bool TryParseInt32(string s, NumberStyles style, NumberFormatInfo info, out int result)
{
    byte* stackBuffer = stackalloc byte[1 * 114 / 1];
    Number.NumberBuffer numberBuffer = new Number.NumberBuffer(stackBuffer);
    result = 0;
    if (!Number.TryStringToNumber(s, style, ref numberBuffer, info, false))
    {
        return false;
    }
    if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
    {
        if (!Number.HexNumberToInt32(ref numberBuffer, ref result))
        {
            return false;
        }
    }
    else
    {
        if (!Number.NumberToInt32(ref numberBuffer, ref result))
        {
            return false;
        }
    }
    return true;
}

As you can see, result is set to 0, this is due to the fact that "not an int" is infact... not an int. With failed conversion-attempts (if you want to look at it that way), this function sets the result to 0.

Joel
  • 5,732
  • 4
  • 37
  • 65
1

As stated in this other question, local variables are not initialized.

As per Microsoft Docs

When this method returns, [result]contains the 32-bit signed integer value equivalent of the number contained in s[entry string], if the conversion succeeded, or zero if the conversion failed.

So after tryparse, n is initialised to the value 0.

rhommet
  • 13
  • 2