#720 – Location of Declarations within A Method Does Matter

When declaring members in a class, you can declare the members anywhere in the class, even placing a declaration after some code that references the declared member.

When you declare variables within a method, however, a variable must be declared before it is used.  Compiling the code below will result in a compile-time error, since the leadin variable in the method RevealNames is declared after it is used.

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

        public Dog(string name)
        {
            Name = name;
            secretName = "His Great Terribleness Mr. Bites-a-Lot";
        }

        public void RevealNames()
        {
            Console.WriteLine(leadin);
            Console.WriteLine(string.Format("{0} is really {1}", Name, secretName));
            string leadin = "Did you know?";
        }

        private string secretName;
    }
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s

%d bloggers like this: