First of all, let me say that I've never used C# before, and I don't know about it much.
I was studying for my "Programming Languages" exam with Sebesta's "Concepts of Programming Languages 9th ed" book. After I read the following excerpt from "Scope declaration order (on 246th page)", I got a little bit puzzled:
"...For example, in C99, C++, Java the scope of all local variables is from their declarations to the ends of the blocks in which those declarations appear. However, in C# the scope of any variable declared in a block is the whole block, regardless of the position of the declaration in the block, as long as it is not in a nested block. The same is true for methods. Note that C# still requires that all variables be declared before they are used. Therefore, although the scope of a variable extends from the declaration to the top of the block or subprograms in which that declaration appears, the variable still cannot be used above its declaration"
Why did designers of C# make such decision? Is there any specific reason/advantage for such an unusual decision?
One of the most significant features of C language is its support for dynamic memory management (DMA). It means that you can utilize and manage the size of the data structure in C during runtime. C also provides several predefined functions to work with memory allocation.
The C programming language is a procedural and general-purpose language that provides low-level access to system memory. A program written in C must be run through a C compiler to convert it into an executable that a computer can run.
This prevents you from doing something such as
void Blah()
{
for (int i = 0; i < 10; i++)
{
// do something
}
int i = 42;
}
The reason is that it introduces the possibility for subtle bugs if you have to move code around, for instance. If you need i
before your loop, now your loop is broken.
One example of a benefit of reduced confusion is that if you have a nested block above the variable declaration, the variable declaration will be in effect and prevent the nested block from declaring a variable with the same name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With