Scope of variable with out parameter

Viewed 3172

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?

2 Answers
Related