Click here to Skip to main content
15,881,173 members
Articles / Programming Languages / C#
Article

Static Keyword Demystified

Rate me:
Please Sign up or sign in to vote.
4.69/5 (155 votes)
5 Oct 20065 min read 419K   136   85
This article aims to clear the confusion regarding the use of the static keyword in C#.

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

C#
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:

C#
MyClass.DoSomething();

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

C#
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:

C#
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:

C#
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:

C#
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:

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++:

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:

C#
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:

C#
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;
    }       
}

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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Founder Axero Solutions LLC
United States United States
Vivek is the co-founder of Communifire, a social business software platform that drives business growth. You can collaborate with anyone, provide better customer support, power your company intranet, build a knowledge base, and launch online communities for anything -- and more -- all in one integrated platform.

Link: http://axerosolutions.com

Comments and Discussions

 
GeneralRe: ...but what about threading? Pin
ttobler3-Oct-06 7:47
ttobler3-Oct-06 7:47 
GeneralRe: ...but what about threading? Pin
jdkulkarni19-Mar-07 22:51
jdkulkarni19-Mar-07 22:51 
GeneralRe: ...but what about threading? Pin
gbahns21-Sep-07 5:09
gbahns21-Sep-07 5:09 
GeneralecStatic :) Pin
RedSunBeer24-Aug-06 2:16
RedSunBeer24-Aug-06 2:16 
GeneralRe: ecStatic :) Pin
Vivek Thakur24-Aug-06 4:17
professionalVivek Thakur24-Aug-06 4:17 
GeneralC++ static variables can be changed Pin
sergey.belov22-Aug-06 11:35
sergey.belov22-Aug-06 11:35 
GeneralRe: C++ static variables can be changed Pin
SmurfButcher Bob29-Sep-06 19:33
SmurfButcher Bob29-Sep-06 19:33 
GeneralRe: C++ static variables can be changed Pin
Vivek Thakur29-Sep-06 20:07
professionalVivek Thakur29-Sep-06 20:07 
GeneralRe: C++ static variables can be changed [modified] Pin
SmurfButcher Bob30-Sep-06 5:53
SmurfButcher Bob30-Sep-06 5:53 
Argh, it'd appear that my brain suffered a 1am parsing error -

> ...static keyword in C++ ... once initialized the variables cannot be changed or re-initialized something like “const” keyword in C#). Also, just like C# and Java, these variables...

- there's a missing ( which caused what I was referring to,

- "Also, just like" is commonly used to demand that the previous statement is associated to that which follows. While not the case with what you wrote, a trick-of-the-eyes as we look for the missing paren makes it so:

...the variables cannot be changed or re-initialized something like “const” keyword in C#). Also, just like C# [back up to look for the open-paren, in the context of "in C#"] cannot be changed or re-initialized something [don't find an open paren, but it'd probably go here. Resume...] Also, just like C# and Java...

We're left with a visual memory/context of a C# static not being changed or re-initted, and resuming at a point that reenforces the C# association with it (because of the "Also"). I consequently used one of your snippets to show that you couldn't have meant to say that, probably due to a typo.

Sorry about that!

You might consider rewording -
---
Similar to C#, the static keyword in C++ is used to specify that variables will be in memory till the time the program ends. Just like C# and Java, C++ static variables don’t need an object to be declared to use them. Once initialized, however, the variables cannot be changed or re-initialized - the C++ "static" behavior is akin to including the “const” keyword in C#.
---

However, I do disagree that C++ statics cannot be changed. Most documents plainly state that a static "can only be initialized once" - and yes... since it is allocated once, it can only be initialized once. If we want a static const, then we declare a "static const"... with the usual caveats about integral types, etc. Otherwise, changing the value after the fact is fine:

class mystuff
{
static int s_pegCounter; // counts # of instances
public:
mystuff();
~mystuff();
private:
void firstOneExists();
void noneExist();
}

int mystuff::s_pegCounter = 0;

mystuff::mystuff()
{
if (!s_pegCounter++) firstOneExists();
}

mystuff::~mystuff()
{
if (!--s_pegCounter) noneExist();
}

There is a potential minefield if dealing with multiple threads, obviously... but that's true no matter what.

Regardless, this article is excellent and very easy to read. Very well done, sir.


"The true definition of madness is repeating the same action, over and over, hoping for a different result." - Einstein.
"Einstein never used Windows." - SBB


-- modified at 11:59 Saturday 30th September, 2006
GeneralRe: C++ static variables can be changed Pin
Vivek Thakur1-Oct-06 1:48
professionalVivek Thakur1-Oct-06 1:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.