#1,102 – Scope vs. Declaration Space

The terms scope and declaration space are similar, but slightly different.

  • Scope is the region of code in which you can refer to a named entity using its unqualified name.
  • Declaration space is a region of code within which you can’t declare two entities having the same name

For example:

    public class MyClass
    {
        int count1 = 1;
        int count2 = 2;

        public void AMethod()
        {
            int count2 = 22;

            Console.WriteLine(count1 + ", " + count2);
        }
    }

Then:

  • The class-level declarations of count1 and count2 are in the same scope and in the same declaration space
  • The body of function AMethod()
    • is included in the scope in which class-level fields are defined, i.e. you can reference them using their unqualified name.
    • defines a new declaration space, i.e. we can define a new variable of the same name as the class-level fields
    • defines a new scope, in which we can define variables, nested within outer scope

1102-001

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.

One Response to #1,102 – Scope vs. Declaration Space

  1. Pingback: #1,104 – Can’t Re-Declare a Variable within a Nested Block | 2,000 Things You Should Know About C#

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: