#1,104 – Can’t Re-Declare a Variable within a Nested Block

A declaration space is a region of code within which you can’t declare two entities having the same name.  

Defining a class creates a new declaration space, i.e. you can declare variables at the class level.

Defining a method creates a new declaration space, known as a local variable declaration space.  A block of code within that method creates a nested local variable declaration space.

It’s of course an error to declare two variables of the same name within a local variable declaration space.  It’s also an error to re-declare a variable of the same name in a nested local variable declaration space.

        public void MethodA()
        {
            int y = 1;
            string y = "oops";  // ERROR

            int x = 12;
            Console.WriteLine(12);

            if (DateTime.Now.DayOfWeek == DayOfWeek.Thursday)
            {
                // ERROR: Can't re-declare x within nested local variable declaration space
                double x = 4.2;
                Console.WriteLine(x);
            }
        }
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

3 Responses to #1,104 – Can’t Re-Declare a Variable within a Nested Block

  1. Pingback: Dew Drop – May 27, 2014 (#1784) | Morning Dew

  2. kai zhou says:

    Good job, “declaration space”, “nested declaration space”. Thank you for the knowledge Sean.

  3. kai zhou says:

    Sorry, it’s “local declaration space” and “nested local declaration space”.

    We can hide a class declaration space variable with a local declaration space variable, but we can’t hide a local declaration space variable with a nested local declaration space variable.

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: