#283 – Instance Methods Can Call Static Methods

Instance methods in a class can access static data or call static methods.  The instance method accesses static data or methods in the same way that other code does–by using the class name to qualify the data or method name.

Here’s an example, where the Dog.Bark instance method makes use of the private static Dog.FormatTheCreed method:

        // Static property -- one value for all dogs
        public static string Creed { get; set; }

        // Private static method to format our Dog creed
        private static string FormatTheCreed()
        {
            return string.Format("As dogs, we believe: {0}", Dog.Creed);
        }

        // Instance method, in which a Dog barks
        public void Bark()
        {
            // Dump out my name and the universal Dog creed.
            Console.WriteLine("{0}: 'Woof'!  (Creed: [{1}])", this.Name, Dog.FormatTheCreed());
        }

Calling the Bark method:

            // Set static property
            Dog.Creed = "We serve man";

            Dog kirby = new Dog("Kirby");
            kirby.Bark();

Advertisement

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

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: