Loading ...

Static Keyword Demystified | CodeAsp.Net

Static Keyword Demystified

(4484)
0
/5
Avg: 0/5: (0 votes)
Published: 2/9/2009 by Vivek Thakur

Introduction

What is the difference between a static class and a static member variable or method? I have asked this question in most of my interviews, and most of the time, it confuses candidates. So I thought of writing an informative article on it so that the difference is comprehensible, and fellow developers can add more information/valuable points.

Static Demystified

Let's start with the memory first. Whenever a process is loaded in the RAM, we can say that the memory is roughly divided into three areas (within that process): Stack, Heap, and Static (which, in .NET, is actually a special area inside Heap only known as High Frequency Heap).

The static part holds the “static” member variables and methods. What exactly is static? Those methods and variables which don't need an instance of a class to be created are defined as being static. In C# (and Java too), we use the static keyword to label such members as static. For e.g.:

class MyClass
{
    public static int a;
    public static void DoSomething();
}

These member variables and methods can be called without creating an instance of the enclosing class. E.g., we can call the static method DoSomething() as:

MyClass.DoSomething();

 We don't need to create an instance to use this static method.

MyClass m = new MyClass();
m.DoSomething();
//wrong code. will result in compilation error. 

An important point to note is that the static methods inside a class can only use static member variables of that class. Let me explain why:

Suppose you have a private variable in MyClass which is not static:

class MyClass
{
// non-static instance member variable
private int a;
//static member variable
private static int b;
//static method
public static void DoSomething()
{
//this will result in compilation error as “a” has no memory
a = a + 1;
//this works fine since “b” is static
b = b + 1;
}
}

 Now, we will call the DoSomething method as:

MyClass.DoSomething();

Note that we have not created any instance of the class, so the private variable "a" has no memory as when we call a static method for a class, only the static variables are present in the memory (in the Static part). Instance variables, such as “a” in the above example, will only be created when we create an instance of the class using the “new” keyword, as:

MyClass m = new MyClass();  //now “a” will get some memory

But since we haven’t created an instance yet, the variable “a” is not there in the process memory. Only “b” and “DoSomething()” are loaded. So when we call DoSomething(), it will try to increment the instance variable “a” by 1, but since the variable isn’t created, it results in an error. The compiler flags an error if we try to use instance variables in static methods.

Now, what is a static class? When we use the static keyword before a class name, we specify that the class will only have static member variables and methods. Such classes cannot be instantiated as they don’t need to: they cannot have instance variables. Also, an important point to note is that such static classes are sealed by default, which means they cannot be inherited further.

This is because static classes have no behavior at all. There is no need to derive another class from a static class (we can create another static class).

Why do we need static classes? As already written above, we need static classes when we know that our class will not have any behavior as such. Suppose we have a set of helper or utility methods which we would like to wrap together in a class. Since these methods are generic in nature, we can define them all inside a static class. Remember that helper or utility methods need to be called many times, and since they are generic in nature, there is no need to create instances. E.g., suppose that you need a method that parses an int to a string. This method would come in the category of a utility or helper method.

So using the static keyword will make your code a bit faster since no object creation is involved.

 An important point to note is that a static class in C# is different from one in Java. In Java, the static modifier is used to make a member class a nested top level class inside a package. So using the static keyword with a class is different from using it with member variables or methods in Java (static member variables and methods are similar to the ones explained above in C#).

Please see the following link for details:

 * Static class declarations

Also, the static keyword in C++ is used to specify that variables will be in memory till the time the program ends; and initialized only once. Just like C# and Java, these variables don’t need an object to be declared to use them. Please see this link for the use of the static keyword in C++:

 * Static: The Multipurpose Keyword
 
Writing about the const keyword brings me to a subtle but important distinction between const and readonly keywords in C#: const variables are implicitly static and they need to be defined when declared. readonly variables are not implicitly static and can only be initialized once. E.g.: You are writing a car racing program in which the racing track has a fixed length of 100 Km. You can define a const variable to denote this as:

private const int trackLength = 100;

 

Now, you want the user to enter the number of cars to race with. Since this number would vary from user to user, but would be constant throughout a game, you need to make it readonly. You cannot make it a const as you need to initialize it at runtime. The code would be like:

 public class CarRace
{
    //this is compile time constant
    private const int _trackLength = 100;
    //this value would be determined at runtime, but will
    //not change after that till the class's
    //instance is removed from memory
    private readonly int _noOfCars;

    public CarRace(int noOfCars)
    {}

    public CarRace(int noOfCars)
    {
        ///<REMARKS>
        ///Get the number of cars from the value
        ///use has entered passed in this constructor
        ///</REMARKS>
        _noOfCars = noOfCars;
    }      
}

I would also like to add a few valuable comments from one of the members (Jon Rista):

Well, you actually started your article off very, very well with this statement:

"Whenever a process is loaded in the RAM, we can say that the memory is roughly divided into three areas (within that process):
 Stack, Heap, and Static (which, in .NET, is actually a special area inside Heap only known as High Frequency Heap)."

Knowing that statics are allocated on the High Frequency Heap is actually pretty critical to answering your question.
The overall answer is yes, ultimately, static classes (or static elements in a class) will perform better than instance
classes (and elements within an instance of a class). Why?

Like I mentioned before, static classes are still JITted and constructed, just like any other normal class.
The JIT part happens when you first use a method or access a static property/field of a static class. This is a
common hit applicable to all classes in a .NET app. After JITting is complete, the class will be constructed (assuming
there is construction to perform...in this area, I'm not actually sure if a .cctor is created for a static class that
does not have any static fields...I'll have to check it out). When a static class is constructed, its member data is
stored in the High Frequency Heap, which is actually not a garbage-collected heap (or object heap)...its whats called
a Loader Heap. Loader heaps are managed differently than an object heap because they are much more predictable,
and don't need nearly as much overhead as an object heap. In addition to storing values of static fields from a
static class, the High Frequency Heap also stores the MethodTables, MethodDescs, and FieldDescs of the static class,
which are part of the CLR type system.

In the event that you just have a static class with no member fields, an "instance" of that static class still must be
compiled (JITted), and loaded (MethodTables, MethodDescs placed in HFH), and in the event that the original 32k reserve
size of the High Frequency Heap is used up (possible in very large applications, and probably with very large volumes of static classes),
the heap will need to be resized when this creation happens. Looking up a method when its called should take the same amount of time that
it takes to look up a method on an instance of a class, since all type information (MethodTables, MethodDescs, FieldDescs, and Interface Maps) for
all types, static or otherwise, are keept in the High Frequency Heap.

Now, with all that said, static classes are still going to be "lighter" than an instance class. Why? Because instance classes are
allocated on the object heap (the GC heap), and any time an instance class becomes unreachable, it will be garbage collected. This
garbage collection will affect the performance of an application whenever it runs. So, as you mentioned in your article, proper use of static classes can help improve the performance of an application a bit. Its just that static classes arn't "free" from a performance standpoint...they still incurr some costs, and since static classes arn't constructed until used (assuming there are static member fields), the cost of JITting, loading types, and loading static fields into the HFH happens the first time that static class is used.

If you want all the nitty-gritty low-level details, take a look at this article: http://msdn.microsoft.com/msdnmag/issues/05/05/JITCompiler/

It should answer any questions you have about the managed runtime and how it handles memory.

Also, another common question is: What is the difference between a static class and a static member variable or method?
A static class is a class which can only contain static members (variables and/or methods). A static variable or method may exist in either a static class, or a normal class. The difference is pretty much the same difference as a class vs. a normal variable or method.Static elements are NOT thread safe. You need to manually make the thread safe using "locks" or similar. There are already dozen of articles on this topic and here is a very good link:http://www.odetocode.com/Articles/313.aspx

Summary

We examined the static keyword in C#, and saw how it helps in writing good code. It is best to think and foresee possible uses of the static keyword so that the code efficiency, in general, increases. 

 

 

Comments (no comments yet)

Top articles

Quick Vote

What kind of email newsletter would you prefer to receive from CodeAsp.Net?