Tuesday, July 28, 2009

Constants vs Static Variables

Today I discussed with my colleague natwar on difference between use of constant variables and static variables.

Sometimes, we declare a class to store constant string and this functionality can also be implemented by using the static keyword.

I have created a small program to demonstrate the same.

Code Listing

namespace TestingApp

{

class Program

{

static void Main( string[] args )

{

Console.WriteLine( ClassWithConsts.HelloWorld );

Console.WriteLine( ClassWithStatic.HelloWorld );

}

}

class ClassWithConsts

{

public const string HelloWorld = "Hello World";

}

class ClassWithStatic

{

public static string HelloWorld = "Hello World";

}

}

After disassembling, we have come to know that, when we use constant variables, Compiler replaces them with their value in the source code.

This is not the case with the static variables, as every time they are used a new instance of the variable type is created and subsequently used.

Check the disassembled code


Now we will use constant variables instead of static for strings which do not change during the executon of the program. Thanks to ILDASM !

[Source Code]