Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of variable with out parameter

Example:

I have the following code block:

if (!int.TryParse("123", out var parsedNumber))
{
    return;
}

Console.WriteLine(parsedNumber);

The output in console is: 123

Question:

How is it possible, that the line Console.WriteLine(parsedNumber); knows about parsedNumber?

According to my understanding, parsedNumber should only available in the if-block, shouldn't it?

If I try this:

foreach (var data in dataList)
{
   data += "something";
}

Console.WriteLine(data);

Console.WriteLine(data); can't find data.


I think, that the solution is the out parameter, but I'm not sure. Can someone explain this?

like image 274
Sean Stayns Avatar asked Jul 08 '17 02:07

Sean Stayns


1 Answers

Yes, as you suspect the difference is that "out" modifier.

It is a feature added in C# 7 that allows you to declare the variable at the point where you want to use it as an argument.

That might be convenient as otherwise you'd have to declare parsedNumber before the method call.

You can read more about it here, under "Out variables".

https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/

EDIT

As for why the variable is still in scope outside of the if, that can certainly be confusing, but it was a design choice when implementing this, specifically for the "if" case and precisely so that it could be used in "try" methods.

You can refer to this comment (actually you can take a look at the whole discussion to see the different points of view there were on how to implement this).

https://github.com/dotnet/roslyn/issues/12939#issuecomment-255650834

like image 67
eugenioy Avatar answered Sep 23 '22 03:09

eugenioy