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?
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
Prior to C# 7.0
the out keyword was used to pass a method argument's reference. Before a variable is passed as an out argument, it must be declared.
var parsedNumber;
if (!int.TryParse("123", out var parsedNumber))
{
return;
}
Console.WriteLine(parsedNumber);
In C# 7.0
you can define a method's out parameters directly in the method. The new code looks like
if (!int.TryParse("123", out var parsedNumber))
{
return;
}
Console.WriteLine(parsedNumber);
Reference :
Whats-new-in-csharp-7-0