#255 – Static Fields vs. Instance Fields

When you declare a field in a class using the syntax below, you get an instance field, meaning that you’ll get one copy of the field’s data for each instance of the class that is created.  The field’s data is stored in the object (an instance of the class).

    public class Dog
    {
        public string Name;    // Instance field
    }

You can also define static fields in a class.  A static field is a variable where we can store a piece of data for the entire class, rather than a piece of data for each instance of the class.

You declare a static field using the static keyword.

    public class Dog
    {
        // Static field
        public static string Motto = "Man's best friend";
    }

With static fields, we always have exactly one copy of the field, no matter how many instances of the class we create.

Advertisements