#695 – Static Methods Can Access Static Members
October 18, 2012 3 Comments
A static method can only access static members in the class that it’s defined in.
(If you pass an instance of an object to a static method, it can invoke instance members on that object).
public class Dog { // Instance properties public string Name { get; set; } public int Age { get; set; } // Instance constructor public Dog(string name, int age) { Name = name; Age = age; } // Instance method public void Bark() { Console.WriteLine("{0} says WOOF", Name); } // Static property public static string DogMotto { get; protected set; } // Static constructor static Dog() { DogMotto = "Serve humans"; } // Static method public static void AboutDogs() { // Accessing static data Console.WriteLine("Dogs believe: {0}", DogMotto); // ERROR: Can't access instance property Console.WriteLine(Name); // ERROR: Can't call instance method Bark(); } }
Trying to access instance methods or data from a static member will generate a compile-time error.
If you wanted to access the instance method Bark(), how would you do it in your example?
Jack, you can’t access instance methods–that was the point of the post. A static method is one that executes without knowing anything about any particular instance. So if our AboutDogs() method is static, it’s not specific to any particular Dog instance. So calling Bark() doesn’t make sense, since we don’t know which Dog we’re talking about.
I read through your previous posts and created an object
Dog spook = new Dog(“Spook”, 11);
and then access the methods using a reference…
Console.WriteLine(spook.Name);
spook.Bark();
Correct?