#259 – Static vs. Instance Properties

A typical property declared in a class is an instance property, meaning that you have a copy of that property’s value for each instance of the class.

You can also define static properties, which are properties that have a single value for the entire class, regardless of the number of instances of the class that exist.

    public class Dog
    {
        // An instance property--one copy for each dog
        public string Name { get; set; }

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

You can read and write a static property even if no instances of the class exist.  You use the class’ name to reference a static property.

            // Writing an instance property  (Name)
            Dog kirby = new Dog();
            kirby.Name = "Kirby";

            Dog jack = new Dog();
            jack.Name = "Jack";

            // Write a static property
            Dog.Creed = "We are best friends to humans.";
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.

One Response to #259 – Static vs. Instance Properties

  1. Pingback: #696 – Using a Static Property to Count Instances « 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: