Scope of Local Variables in C# and C++
Consider the following code in C++:
This code actually compile and the output is the following:
The important thing to notice here is that in C++ is possible to declare a variable with the same name in a nested block.
“A name declared in a block is local to that block; it has block scope. Its potential scope begins at its point of declaration and ends at the end of its block. A variable declared at block scope is a local variable.”
In C# this is not possible. The following code does not compile:
In C# you cannot declare another local variable with the same name in the current block or in any nested blocks. In addition, the variable scope extends in both directions throughout its code block.
Even the following code does not compile:
I would say that the restriction imposed by C# is good and avoid unexpected behaviours in some situations. It also encourages to use meaningful names for variables avoiding to reuse the same variable for different purposes.
However, the following C# code compiles:
This because the two blocks are not related to each others. They are not part of the same chain of nested blocks. This is good because there is a typical situation when you like to reuse the same variable name in loops.
This code compiles:
Permanent link to this article: https://www.productivecsharp.com/2012/11/scope-of-local-variables-in-c-and-c/
: in_array() expects parameter 2 to be array, null given in /home/andreaa9/public_html/wp-content/themes/graphene/inc/plugins.php
on line 92