#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
            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.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #695 – Static Methods Can Access Static Members

  1. Jack Moorhead says:

    If you wanted to access the instance method Bark(), how would you do it in your example?

    • Sean says:

      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.

  2. Jack Moorhead says:

    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?

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: