C# Static Fields


This entry is part 4 of 8 in the series C# Classes Intermediate

We have a series of posts that contain more introductory content than this series of posts called C# Introduction.

Typically when you first learn about classes you work with instance classes. First, you define a class (or use one in .NET) and then you make an instance of that class in memory. You might then initialize it. This is the default. Instance classes are the default.

However, fields can be declared using the static keyword, as in public static int MyInt;. What does static mean? Static fields are accessed via the class that defines them (MyClass.MyInt) not through object instances of the class. You can also use the keyword const to create a constant value. const members are static by definition and you will get an error if you also add the static modifier when you use const.

Besides instance fields, classes can have what are called static fields. A static field is shared by all the instances of the class, and all the instances access the same memory location. Hence, if the value of the memory location is changed by one instance, the change is visible to all the instances. Use the static modifier to declare a field static.

For example, the code in the figure from the book Illustrated C# 7, Fifth Edition by Daniel Solis and Cal Schrotenboer published by Apress, on page 133, declares class D with static field Mem2 and instance field Mem1. Main defines two instances of class D. The figure shows that static field Mem2 is stored separately from the storage of any of the instances. The gray fields inside the instances represent the fact that, from inside an instance method, the syntax to access or update the static field is the same as for any other member field.

Instance members come into existence when the instance is created and go out of existence when the instance is destroyed. Static members, exist and are accessible even if there are no instances of the class. Static fields with no class instances can still be assigned to and read from because the field is associated with the class, not an instance.

using System;
namespace StaticFields
{
    class Program
    {
        static void Main(string[] args)
        {
            D.Mem2 = 17;
            Console.WriteLine(D.Mem2);
            // Console.WriteLine(D.Mem1); DOES NOT COMPILE
        }
        public class D
        {
            public int Mem1 = 9;
            static public int Mem2;
        }  // OUTPUT: 17
    }
}
Series Navigation<< C# Class Constructor OverloadingC# Static Methods >>