#281 – Declaring and Using Static Methods in a Class

A static method in a class is similar to an instance method, except that it acts upon the class’ static data–fields and properties–rather than on the instance data stored with a single instance of the class.

There is only one copy of each static data item, no matter how many instances of the class exist.

Here’s an example of defining a static method in a class.

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

        // Static method acts on static data
        public static void RepeatYourCreed(int numRepeats)
        {
            for (int i = 0; i < numRepeats; i++)
                Console.WriteLine("My creed is: {0}", Creed);
        }

To call a static method, you just prefix the method with the name of the class (rather than with a reference to an instance of the class).

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

            // Call static method
            Dog.RepeatYourCreed(3);
Advertisement

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

One Response to #281 – Declaring and Using Static Methods in a Class

  1. Pingback: #695 – Static Methods Can Access Static Members « 2,000 Things You Should Know About C#

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: