#608 – Instance Methods Can Use Static Data
June 19, 2012 Leave a comment
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; TotalNumDogs++; } 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); } }