#695 – Static Methods Can Access Static Members

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

            // ERROR: Can't call instance method

Trying to access instance methods or data from a static member will generate a compile-time error.