Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question on C# Variable Scope vs. Other Languages

Tags:

scope

c#

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?

like image 828
kolistivra Avatar asked Jun 04 '10 18:06

kolistivra


People also ask

What is the main point of C?

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.

What is C program short answer?

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.


2 Answers

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.

like image 112
Anthony Pegram Avatar answered Nov 09 '22 15:11

Anthony Pegram


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.

like image 44
David Gladfelter Avatar answered Nov 09 '22 17:11

David Gladfelter