#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.

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: