#609 – Omit the Class Name for Static Members in the Same Class
June 20, 2012 Leave a comment
Normally when you reference static members, you use the class name where they are defined to prefix the name of the member. For example, if we have a static property in the Dog class called Motto and a static method called ListAllDogs, we’d use these static members from another class as follows:
public class Program { static void Main() { // Reference static members in Dog from outside of Dog class Console.WriteLine("Dog motto: {0}", Dog.Motto); Dog.ListAllDogs(); } }
However, if we access these static members from code within the Dog class itself, we can omit the class name when referencing the static members.
// Dog.Bark public void Bark() { Console.WriteLine("{0} says Woof", Name); // Reference static members from within Dog class Console.WriteLine("Dog motto: {0}", Motto); ListAllDogs(); }