C# again: does declaration order matter in a C# program?

(that”s what someone asked me today)

And the answer is…yes and no. I”ve went to the specs to confirm my thoughts and according to it, the order declaration matters only in the following scenarios:

  • fields: the way you put your fields in the class specifies the order in which they”re initialized;
  • local variables must be initialized before they are used;
  • for enumerations, the order is important if you don”t specify its constant values explicitly.

1 and 3 are relatively obvious, but what about the 2nd? If you can build a class and put all its fields at the end and the methods at the top, why can”t you do something like this:

class Test {
   public void Test() {
       i = 20; //error here!
       int i;
       i = 30;
   }
   int i;
}

The answer to this question is on the item 3.7 of the spec which talks about scopes. Allowing this sort of thing could introduce some bugs. If it was possible, then it would mean that when you”re writing i = 20, you”d actually be updating the i field of the class (this.i) and then you”d be working on the i variable (ie, when you”re setting i = 30). Or didn”t you want to do this? Now, that doesn”t look too good, right? So, that”s why the scope of a variable is the block where it”s define and in this case the declaration order does matter.

btw, there”s one thing that might make the previous sample work (ie,where you could set the i field to 20 and then declare the i variable). Take a look at this modified version:

class Test {
   public void Test() {
       this.i = 20; //no error: accessing this.i
       int i;
       i = 30;
   }
   int i;
}

Advertisements

~ by Luis Abreu on September 3, 2007.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: