9 Key Concepts to Keyword 'Static'

Preface

When we talk about the Object Oriented Programming (OOP) methodology, suddenly our mind strikes with Abstraction, Encapsulation, Polymorphism and Inheritance. And as Coffee blends more people on table, discussion tends to stretch one level more with data hiding, overloading, overriding, abstract classes and sealed classes. In my experience, every time I have revisited this jargon, I come across the unknown corner that left me surprised. One of such keywords is “Static”. It starts with the simple concept of “Sharing” but in depth, it leads to some surprising results. Today we will explore these concepts.

Disclaimer: This article covers the concepts of the static keyword with respect to the C# programming language. Some of these concepts may not be applicable to other high-level programming languages.

Before we begin

For those of you with little or no idea about the keyword static, I would like to brush upon the concepts.

For example, we have the following DistanceConverter class that has one of the methods called GetDistanceInKM() that accepts the distance in Miles and converts them to KM (Kilometers).
  1. /// <summary>  
  2. /// Converts distance from one unit to another  
  3. /// </summary>  
  4. public class DistanceConverter  
  5. {  
  6.     float _multiplier = 1.60934F;  
  7.   
  8.     /// <summary>  
  9.     /// Return the distance in KM  
  10.     /// </summary>  
  11.     /// <param name="distanceInMiles">Distance in Miles</param>  
  12.     /// <returns></returns>  
  13.     public float GetDistanceInKM(float distanceInMiles)  
  14.     {  
  15.         return (_multiplier * distanceInMiles);  
  16.     }  
  17. }  
Main() function
  1. class Program  
  2. {  
  3.         static void Main()  
  4.         {  
  5.             DistanceConverter objD1 = new DistanceConverter();  
  6.             Console.WriteLine("D1:" + objD1.GetDistanceInKM(2));  
  7.   
  8.             DistanceConverter objD2 = new DistanceConverter();  
  9.             Console.WriteLine("D2:" + objD2.GetDistanceInKM(3));  
  10.   
  11.             DistanceConverter objD3 = new DistanceConverter();  
  12.             Console.WriteLine("D3:" + objD3.GetDistanceInKM(4));  
  13.   
  14.             Console.ReadLine();  
  15.         }  
  16.  }  
As you can see from Main() we have created multiple objects of the class DistanceConverter. Here is the behind-the-scenes memory allocation.

DistanceConverter

As you can see object objD1, objD2 and objD3 are all using the same field and the same method. It's just that they happen to pass various values of distance in miles to get the distance in KM. In a closer look, the value for the field _multiplier is the same. If we were to create another 100, 200 or 1000 objects, the value of field _multiplier would have been the same repeated all over. But wait, that's a bad use of memory! In true sense, it would be nice to have 1 copy of _multiplier shared across all the instances of the class. Just as shown in the diagram below:

diagram

And hence the concept, the concept of sharing referred to as Static or Shared (in the VB.NET world) field or variable. Similarly we can have constructors, methods, properties or even entire classes shared. If we were to do this programmatically, we will use the static keyword as shown below:
  1. /// <summary>  
  2. /// Converts distance from one unit to another  
  3. /// </summary>  
  4. public class DistanceConverter  
  5. {  
  6.     static float _multiplier = 1.60934F;  
  7.   
  8.     /// <summary>  
  9.     /// Return the distance in KM  
  10.     /// </summary>  
  11.     /// <param name="distanceInMiles">Distance in Miles</param>  
  12.     /// <returns></returns>  
  13.     public float GetDistanceInKM(float distanceInMiles)  
  14.     {  
  15.         return (_multiplier * distanceInMiles);  
  16.     }  
  17. }  
In the example above, _multiplier is static and hence referred to as Static member of the class  whereas the GetDistanceInKM() method is non-static and hence referred to as an instance member of the class. With this example, we have tried to see the significance of the keyword static. Let's return to our main discussion and explain the key concept of the keyword static that is worth remembering.

1. Applicability 

A class can be static but a structure and interface cannot be. Similarly, constructors, fields, properties and methods can be static but destructors cannot be.

We can have static classes, fields, properties, constructors and methods.
  1. /// Static class  
  2. static class StaticClass  
  3. {  
  4.     //Some class members  
  5. }  
  6.   
  7. public class SomeClass  
  8. {  
  9.     //Static Field  
  10.     static int intstatic = 0;  
  11.   
  12.     //Static Property  
  13.     public static string StaticProperty { getset; }  
  14.   
  15.     //Static Constructor  
  16.     static SomeClass()  
  17.     { }  
  18.   
  19.     //Static Method  
  20.     public static void DoSomething()  
  21.     {  
  22.         Console.WriteLine(intstatic);  
  23.     }  
  24. }  
But we cannot have static interfaces, structures or destructors.
  1. /// Trying to declare static Interface  
  2. static interface IStaticInterface  
  3. {  
  4.     //some interface members  
  5. }  
  6.   
  7. /// Trying to declare static structure  
  8. static struct StaticStruct  
  9. {  
  10.     //some structure member  
  11. }  
  12.   
  13. /// Some Random class  
  14. class SomeClass1  
  15. {  
  16.     /// Trying to declare static Destructor  
  17.     static ~SomeClass1()  
  18.     { }  
  19. }  
If we try to create one, we will get the following compilation error:

    ” The modifier 'static' is not valid for this item”

Later, we will also explain why such implementation does make sense.  

2. Access Modifiers

A static constructor does not have access modifiers. Other static elements do.

We can have static classes, fields, properties and methods denoted with the access modifier. But if you do so with a static constructor as in the following:
  1. //Static class with Access Modifier  
  2. public class SomeClass  
  3. {  
  4.     //Static Field with Access Modifier  
  5.     public static int intstatic = 0;  
  6.   
  7.     //Static Property with Access Modifier  
  8.     public static string StaticProperty { getset; }  
  9.   
  10.     //Trying to declare static Constructor with Access Modifier  
  11.     public static SomeClass()  
  12.     { }  
  13.   
  14.     //Static Method with Access Modifier  
  15.     public static void DoSomething()  
  16.     {  
  17.         Console.WriteLine(intstatic);  
  18.     }  
  19. }  
It will result in the following compilation error.

    ”Access modifiers are not allowed on static constructors”

Also, if you notice, so far I have used word the constructor but not constructor(s). Why? We will see next.

3. Unique Static Constructor

A class can have only one static constructor and that too is parameterless.

If we use overloading, we can have multiple constructors, each having a different signature. If we try to mark them static as in the following:
  1. public class SomeClass  
  2. {  
  3.     /// Static Constructor without parameters  
  4.     static SomeClass()  
  5.     {  
  6.         //Do something  
  7.     }  
  8.   
  9.     /// Trying to declare Static Constructor with parameters  
  10.     static SomeClass(int input)  
  11.     {  
  12.         //Do something  
  13.     }  
  14. }  
We will get the compilation error:

    "A static constructor must be parameterless”

So, a class cannot have a static constructor with parameter(s) and hence it can have only one static constructor and that is parameterless.

4. Priority - Static vs Instance Constructor 

A static constructor executes well before an instance constructor and only executes once.

Let's create one simple program to prove this:
  1. public class SampleClass  
  2. {  
  3.     //Static Constructor  
  4.     static SampleClass()  
  5.     {  
  6.         Console.WriteLine("This is SampleClass Static Constructor.");  
  7.     }  
  8.   
  9.     //Instance Constructor  
  10.     public SampleClass()  
  11.     {  
  12.         Console.WriteLine("This is SampleClass Instance Constructor.");  
  13.     }  
  14. }  
  15.   
  16. class Program  
  17. {  
  18.     static void Main()  
  19.     {  
  20.         SampleClass objC1 = new SampleClass();  
  21.         SampleClass objC2 = new SampleClass();  
  22.         SampleClass objC3 = new SampleClass();  
  23.   
  24.         Console.ReadLine();  
  25.     }  
  26. }  

Output of this program is as follows:

program

As you can see, that static constructor was first to execute and only executes once. We will again revisit this point. Especially the words “well before”.

5. Accessibility

Instance members are accessed with a class object outside the class definition and "this" keyword inside the class definition whereas static members can be directly accessed with a class name outside and inside the definition.

This is an important point and it makes sense also since static members are independent of instance objects.
  1. public class SampleClass {  
  2.     public string instanceMsg = "This is instance Field.";  
  3.     public static string staticMsg = "This is static Field";  
  4.   
  5.     public SampleClass()  
  6.     {  
  7.         // Access within class definition  
  8.         Console.WriteLine("Within class instanceMsg:{0}",   
  9.                             this.instanceMsg);  
  10.         Console.WriteLine("Within class staticMsg:{0}",   
  11.                             SampleClass.staticMsg);  
  12.     }  
  13. }  
  14.   
  15. class Program  
  16. {  
  17.     static void Main()  
  18.     {  
  19.         SampleClass ObjS1 = new SampleClass();  
  20.   
  21.         // Access outside class definition  
  22.         Console.WriteLine("From Main Program instanceMsg: {0}",   
  23.                             ObjS1.instanceMsg);  
  24.         Console.WriteLine("From Main Program staticMsg: {0}",   
  25.                             SampleClass.staticMsg);  
  26.   
  27.         Console.ReadLine();  
  28.     }  
  29. }  
We will revisit this in future sections.

6. Compatibility – Static vs Instance members/container

An instance member cannot be created or accessed from a static container whereas static members can be created or accessed from an instance container.

Subheading is not clear! Don't worry. Let's understand this with some examples.

In Scenario 1, we are trying to access the static field iInc within the instance method DoSomething().
  1. // This compiles successfully     
  2. public class InstanceContainerStaticMember  
  3. {  
  4.     static int iInc = 0;  
  5.       
  6.     // Instance Container Method  
  7.     public void DoSomething()  
  8.     {  
  9.         // Static Member  
  10.         iInc++;  
  11.         Console.WriteLine("iInc:{0}", iInc);  
  12.     }  
  13. }  
On the other hand, in Scenario 2, we tried to access an instance member iInc within the static method DoSomething().
  1. // This will result in compilation Error  
  2. public class StaticContainerInstanceMember  
  3. {  
  4.     int iInc = 0;  
  5.   
  6.     /// Static Container Method  
  7.     public static void DoSomething()  
  8.     {  
  9.         //Instance Member  
  10.         iInc++;  
  11.         Console.WriteLine("iInc:{0}", iInc);  
  12.     }  
  13. }  
But when we compiled, Scenario 2 throws the following compilation error.

    “An object reference is required for the non-static field, method, or property”

So the compilation error is clear that we cannot access an instance member from a static container. Why? We will explore this with an example. Recall point 5. According to that, static members are referred to with a class name. So in the example below:

  1. public class SampleClass {  
  2.     private int _id;  
  3.   
  4.     public SampleClass(int ID)  
  5.     {  
  6.         _id = ID;  
  7.     }  
  8.   
  9.     public static void StaticMethod()  
  10.     {   
  11.         //I want to access _id but who will provide me  
  12.     }  
  13. }  
  14. class Program  
  15. {  
  16.     static void Main()  
  17.     {  
  18.         SampleClass s1 = new SampleClass(1);  
  19.         SampleClass s2 = new SampleClass(2);  
  20.         SampleClass s3 = new SampleClass(3);  
  21.   
  22.         //What will be the value for this s1, s2 or s3  
  23.         SampleClass.StaticMethod();  
  24.     }  
  25. }  
We have SampleClass that has a non-static field _id and static method StaticMethod() that wants to access _id. In the Main() program, there are the 3 objects s1, s2 and s3 created of the class SampleClass. And hence the value for _id will be 1, 2 and 3 for the objects s1, s2 and s3 respectively. Now the program makes calls to the SampleClass.StaticMethod(). Since it is called with the class name, if the static method were allowed access to _id, which _id value should it return, s1, s2 or s3? No, it cannot return any since StaticMethod() is independent of the class objects and hence independent of instance members and so the compiler shows the error. This holds true for static classes as well. A static class cannot have an instance member such as fields, properties, constructors or methods. Try it yourself!

7. Object creation and Instantiation

A static class object can neither be created nor instantiated.

Since a static class cannot have instance members, it cannot be instantiated. In the example below, we are trying to create an instance of the class SampleClass.
  1. public static class SampleClass {   
  2.     //static class members  
  3. }  
  4.   
  5. class Program  
  6. {  
  7.     static void Main()  
  8.     {  
  9.         //This statement will result compilation error.  
  10.         SampleClass s1 = new SampleClass();  
  11.     }  
  12. }  
We get the compilation error:

    Cannot declare a variable of static type 'SampleClass'
    Cannot create an instance of the static class ‘SampleClass'

Important

When building an application, you will encounter code blocks that are repetitively used in the application but don't belong to a specific code hierarchy. Usually developers refer to them as utility functions. They serve general utility purposes in the application. You certainly want to modularize such code. At the same time, you want to access these functions without any object creation. Static classes are great to organize these functions. In the Microsoft .NET Framework, one of the great examples of the utility class is the Math class. See the screenshot below:

Math class

8. Inheritance

A static class cannot be part of an inheritance. It cannot serve as a base class, child class or implement an interface.

Yes that's true. As always, let us see by the following examples.

Case 1: A static class cannot be a base class.
  1. public static class BaseClass   
  2. {   
  3.     //Class member goes here  
  4. }  
  5. public class DeriveClass : BaseClass  
  6. {   
  7.     //Class member goes here  
  8. }  
 “Cannot derive from static class 'BaseClass'”

Case 2:
A static class cannot be a derived class.
  1. public class BaseClass  
  2. {  
  3.     //Class member goes here  
  4. }  
  5. public static class DeriveClass : BaseClass  
  6. {  
  7.     //Class member goes here  
  8. }  
Static class 'DeriveClass' cannot derive from type 'BaseClass'. Static classes must derive from object.”.

Case 3: A static class cannot implement interfaces.
  1. public interface IInterface  
  2. {  
  3.     //Interface member goes here  
  4. }  
  5. public static class DeriveClass : IInterface  
  6. {  
  7.     //Class member goes here  
  8. }  
“'DeriveClass': static classes cannot implement interfaces”

That's clear except for one question. As we have seen, a static class cannot be a part of an inheritance hierarchy, then what will happen to protected members in the static class? The answer is a static class cannot have protected members. If you try to declare one, it will throw:
  1. public class BaseClass  
  2. {  
  3.     public static virtual void StaticMethod()  
  4.     { }  
  5. }  
  6.   
  7. public class DerivedClass : BaseClass  
  8. {   
  9.     public override void StaticMethod()  
  10.     { }  
  11. }  
Compilation error.
 
Static classes cannot contain protected members

In fact, static members in non-static classes cannot be overridden.
  1. public class BaseClass  
  2. {  
  3.     public static virtual void StaticMethod()  
  4.     { }  
  5. }  
  6.   
  7. public class DerivedClass : BaseClass  
  8. {   
  9.     public override void StaticMethod()  
  10.     { }  
  11. }  
Compilation error:
 
A static member cannot be marked as override, virtual, or abstract
 

 9. Lifetime

Static elements are in scope as soon as they are referred to in a program for the first time and will remain in scope throughout the life of the AppDomain.

This is an important concept to understand the scope of static elements but I will explain something more than that. Have a look at the example below.
  1. public class SampleClass  
  2. {  
  3.     static int _iCount = 0;  
  4.   
  5.     static SampleClass()  
  6.     {  
  7.         Console.WriteLine("This is Static Ctor");  
  8.     }  
  9.   
  10.     public void SetValue(int Count)  
  11.     {  
  12.         _iCount = Count;  
  13.     }  
  14.   
  15.     public static void Print()  
  16.     {  
  17.         Console.WriteLine("The value of Count:{0}",  
  18.                             SampleClass._iCount);  
  19.     }  
  20. }  
In the class above, we have a static field _iCount and static method Print(). In the Main() program below, we are making a call to the functions function1() and function2(). In both of the functions, we are creating an object of the class SampleClass.
  1. class Program  
  2. {  
  3.     static void Main()  
  4.     {  
  5.         Console.WriteLine("First line in Main().");  
  6.         SampleClass.Print();  
  7.         function1();  
  8.         function2();  
  9.         SampleClass.Print();  
  10.         Console.WriteLine("Last line in Main().");  
  11.         Console.ReadLine();  
  12.     }  
  13.   
  14.     public static void function1()  
  15.     {  
  16.         Console.WriteLine("First line in function1().");  
  17.         SampleClass objS2 = new SampleClass();  
  18.         objS2.SetValue(1);  
  19.         Console.WriteLine("Last line in function1().");  
  20.     }  
  21.   
  22.     public static void function2()  
  23.     {  
  24.         Console.WriteLine("First line in function2().");  
  25.         SampleClass objS3 = new SampleClass();  
  26.         objS3.SetValue(2);  
  27.         Console.WriteLine("Last line in function2().");  
  28.     }  
  29. }  
And finally the following is the output of this program.

output of this program

A couple of interesting observations:
  • The second line of output is the call to the static constructor (see “This is static Ctor”). But if you refer to the Main() function, we are neither creating the object nor instantiating it. Even SampleClass is not declared as static. Yet, the program makes a static constructor call. Remember in Point 4, we discussed that a static constructor is called well before the instance constructor. The word “well before” is important since it suggests that as soon as static elements are accessed (with or without object creation), the constructor will initialize and then the static objects will be in scope but not as soon as the program begins executing. Because the first line in the output (in other words “First line in Main().”) is the Main() function Console.writeline() statement and then the constructor of SampleClass is called. To conclude, static elements are in scope as soon as they are referred to by the program in any way.

  • Also, there are the objects ObjS2 and ObjS3 created in function1() and function2() respectively. Ideally their scope is within the respective function body only. But when we print the value of the _iCount in Main(), the printed value “2” is set by function2() (in other words objS3.SetValue(2)).

So the take-a-way from the last point is that a static element remains active until the last line of the program is executed. Our assumption is absolutely right with respect to this program. The reason being, the scope of our program is limited to one AppDomain. However if we introduce a different AppDomain, things will change. Let's see another example.

Assume we have one class library project.

  1. namespace RemoteClassLibrary  
  2. {  
  3.     public class RemoteClass  
  4.     {  
  5.         static int _myID = 0;  
  6.   
  7.         public RemoteClass()  
  8.         {  
  9.             Console.WriteLine("My ID is {0}", ++_myID);  
  10.         }  
  11.     }  
  12. }  
And we have saved the class library DLL to the local drive c:\app\. We have also created another program that uses reflection to execute this code.
  1. using System.Reflection;  
  2.   
  3. namespace TestingProgram  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main()  
  8.         {  
  9.             const string ClassLibraryPath = @"c:\app\RemoteClassLibrary.dll";  
  10.   
  11.             //Load assembly in current App Domain  
  12.             Assembly Assembly1 = Assembly.LoadFrom(ClassLibraryPath);  
  13.             Assembly1.CreateInstance("RemoteClassLibrary.RemoteClass");  
  14.   
  15.             //Load assembly in current App Domain  
  16.             Assembly Assembly2 = Assembly.LoadFrom(ClassLibraryPath);  
  17.             Assembly2.CreateInstance("RemoteClassLibrary.RemoteClass");  
  18.   
  19.             Console.ReadKey();  
  20.         }  
  21.     }  
  22. }  
And the obvious output of this program is:

obvious output

Please note that even though that assembly is loaded, static members still persist the value, or you can say only a single copy of the static class is created.

Now let's modify the main program to introduce multiple AppDomains that will load this assembly separately.
  1. class Program  
  2. {  
  3.     static void Main()  
  4.     {  
  5.         const string ClassLibrary = "RemoteClassLibrary.RemoteClass";  
  6.         const string ClassLibraryPath = @"c:\app\RemoteClassLibrary.dll";  
  7.   
  8.         //Load class Library in AppDomain1  
  9.         AppDomain AppDomain1 = AppDomain.CreateDomain("AppDomain1");  
  10.         AppDomain1.CreateInstanceFrom(ClassLibraryPath, ClassLibrary);  
  11.   
  12.         //Load class Library in AppDomain2  
  13.         AppDomain AppDomain2 = AppDomain.CreateDomain("AppDomain2");  
  14.         AppDomain2.CreateInstanceFrom(ClassLibraryPath, ClassLibrary);  
  15.   
  16.         Console.ReadKey();  
  17.     }  
  18. }  
Surprisingly the output:

output

And so even though a single program is executing, the different AppDomain is causing the program to maintain 2 copies of the static member per AppDomain. In short, their scope is limited to the AppDomain.

On final note, we explained that the static elements are in scope as soon as they are accessed first and limited to a specific AppDomain.

Why interfaces, structures and destructors cannot be static?

I've said in Point 1 that interfaces, structures and destructors cannot be static and I intentionally left the discussion without adding more details because we need to have enough of a base before we can explain that. Now that we've visited some of the key concepts of static members, this is a mature point to explain in detail.

An interface sets up guidelines and expectations for the implementing classes of what their capabilities should be. If a class is a Blueprint for the object then an interface provides outlines/contracts for the classes. To justify, interfaces describe an object's capabilities but doesn't provide the object representation.

To make it clearer, let's see an example.
  1. public interface IVehicle  
  2. {  
  3.     void Drive();  
  4. }  
  5.   
  6. public class Car : IVehicle  
  7. {  
  8.     public void Drive()  
  9.     {  
  10.         Console.WriteLine("I am Driving Car");  
  11.     }  
  12. }  
  13.   
  14. public class Bike : IVehicle  
  15. {  
  16.     public void Drive()  
  17.     {  
  18.         Console.WriteLine("I am Riding Bike");  
  19.     }  
  20. }  
As you can see in the example above, the interface IVehicle provides a contract for Classes Car and Bike. And Car and Bike provide their native representation. IVehicle doesn't have its own representation but can ask Car and Bike to provide their own representation.
  1. class Program  
  2. {  
  3.     static void Main()  
  4.     {  
  5.         IVehicle vehicle1 = new Car();  
  6.         vehicle1.Drive();  
  7.         //I am Driving Car  
  8.   
  9.         IVehicle vehicle2 = new Bike();  
  10.         vehicle2.Drive();  
  11.         //I am Riding Bike  
  12.   
  13.         Console.Read();  
  14.     }  
  15. }  
Now for the sake of understanding, even if we assume that IVehicle is allowed to have a static something, it would not have an object representation since a static type cannot be instantiated (remember Point 7) and IVehicle.Drive() will not have the representation. Thus semantically, a static interface doesn't make sense.

Coming to structures, structures are separate from the class with respect to the way they are represented in memory. Structures are value types and classes are reference types. Since we cannot have an instance of a static type, the result of a static class and static struct would be the same representation. It will cause unnecessary repetition and confusion.

Finally, destructors are intended for object memory cleanup (to free up resources). Static types don't have an object representation and so we don't need static destructors just like structures (value types) don't have destructors.

Final Words

We have begun with the simple concept of sharing the variables across all the objects of a class but then we made a deep dive into each scenario that this simple concept results in and that certainly leaves us by surprise. To provide you with a more precise example, it's just like a client is proposing to implement a simple program but then over the period when you build, test, revisit and deliver, you will realize how much details are required to finish the simple program. In our entire discussion, I have tried to show everything with an example to make it short, simple and yet effective. If you have anything that promises to change the article title from “9 Key Concepts” to 10, 11, 12 or even more, let me know. I will be more than happy to add your suggestion, input and comments.

Happy Learning!

Version History

Version 1.0: Initial article submitted.
Version 1.1: The following Changes.
  • Added "Why Interface, structure and destructor cannot be static?".
  • Point 8: Added Explanation for "Protected member of class" along with "Virtual" and "Override".
  • Point 9: Elaborate scope of "Static element scope" to "AppDomain".

Recommended Ebook

Printing in C# Made Easy

Download Now!
Similar Articles