Search code examples
c#out

how does the out keyword determine scope for a variable that was not declared before being passed?


When I call a function that takes an out argument and I don't declare the variable used as the argument before calling it, what is the scope of the new variable?

I've noticed I can do this:

if (functionTakesOut(out int newInteger)) {
  Console.WriteLine(newInteger);
}
Console.WriteLine(newInteger);

and both Console.WriteLine() calls will work.


Solution

  • In the example your using the scope would be local...because your declaring it as you pass it.

    Essentially its the same as:

    int newInteger;
    if (functionTakesOut(out newInteger)) 
    {
      Console.WriteLine(newInteger);
    }
    Console.WriteLine(newInteger);