C#: Scope and declaration space

This entry is part 27 of 71 in the series C#

In C#, both scope and declaration space is defined by a statement block enclosed by braces. That means namespaces, classes, methods, and properties all define both a scope and a declaration space.

As a result, scopes can be nested and overlap each other.

If scope defines the visibility of a name and scopes are allowed to overlap, any name defined in an outer scope is visible to an inner scope, but not the other way around.

Consider the following example:

using System;

namespace Friend
{
    class Contact
    {
        public int age;

        public void Mitchell()
        {
            age = 18;
        }

        public void Michael()
        {
            int age;

            age = 22;
        }

        static void Main()
        {
            Contact contact = new Contact();
            Console.WriteLine(contact.age);
            contact.Mitchell();
            Console.WriteLine(contact.age);
            contact.Michael();
            Console.WriteLine(contact.age);
            Console.ReadLine();
        }
    }
}

The output from running the above code will be 0,18,18.

In line 27,28:

            contact.Michael();
            Console.WriteLine(contact.age);

A call to contact.Michael() will not alter the global age variable as member function Michael() has its own local variable declaration age in line 16.

Declaration Space

Declaration space is an enclosing context such as 2 braces in which no two entities are allowed to have the same name.

For example, you could not declare another variable named age in the body of class Contact.  However, you could redeclare the variable age in the sub body of Mitchell or Michael as they are member functions of class Contact.

Redeclaring variables there will make them local variables of Mitchell or Michael.

Series Navigation<< C#: Variable scope in nested block
C#: get and set accessors >>