#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();

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: