#608 – Instance Methods Can Use Static Data

Instance methods in a class can make use of any of the public or private static data that belongs to that class.  (They can also make use of static data from other classes, provided that it is accessible).

    public class Dog
        // Instance Properties
        public string Name { get; set; }
        public int Age { get; set; }

        // Static property
        public static Dog LastGuyThatBarked { get; protected set; }

        // Public static data
        public readonly static string TheDogMotto = "Man's Best Friend";

        // Private static data
        private static int TotalNumDogs = 0;

        public Dog(string name, int age)
            Name = name;
            Age = age;

        public void Bark()
            Console.WriteLine("{0} says Woof", Name);

            // Access static property
            Dog.LastGuyThatBarked = this;

            // Access static data
            Console.WriteLine("There are {0} total dogs", Dog.TotalNumDogs);
            Console.WriteLine("Remember our motto: {0}", Dog.TheDogMotto);

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 )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: