#722 – Local Variable Declarations May Not Always Hide Class Members

A local variable declaration in a method may hide a class member in the containing class, if the two names are the same.  In general, a declaration within an inner scope may hide a member within the outer (containing) scope.

A inner declaration might not hide an outer member, however, if one of the names can be invoked (e.g. a method) and one cannot be invoked (e.g. a variable declaration).

In the example below, the local variable Name in the inner scope does not hide the method Name in the outer scope.

    public class Dog
    {
        public string MyName { get; set; }

        public void Name(string name)
        {
            MyName = name;

            Console.WriteLine(string.Format("New name is {0}", MyName));
        }

        public void Bark()
        {
            // Local variable does not hide Dog.Name method
            string Name = "Franklin Roosevelt";

            Console.WriteLine(Name);

            this.Name("Bob");
        }
    }

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.

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: