#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

#200 – Static Data and Constants Are Stored on the Heap

Static data and constants defined in a C# program are stored on the heap.  Since they exist for the lifetime of the application, they do not need to be garbage collected and are therefore stored in a loader heap, rather than the normal Garbage Collected heap.  Specifically, static data is stored on  the high-frequency heap–one of the loader heaps that exists for each AppDomain.