<Blog:SatheeshBabu LiveAt="India"></Blog>    CodeDigest.com Latest 

Articles

         

Wednesday, October 19, 2005

Const Variable:

Const Variable does not have memory space associated with it.It is similar to #define macro in C.During Compilation the value of const variable are substituted in the place where it is used in the MSIL.This is the reason for which the const variable is initailised before compilation.

Consider the follow code:

int n = 10;
Console.WriteLine(n);

When we compile the above code csc.exe will generate this MSIL:

ldc.i4.10 //Loads the integer value 10
stloc.0 //Stores it to the variable n
ldloc.0 //Loads Back to the execution stack
call void [mscorlib]System.Console::WriteLine(int32) //To print

Consider the follow code with const declaration,

const int n = 5;
Console.WriteLine(n);

the MSIL generated will be:

ldc.i4.10
call void [mscorlib]System.Console::WriteLine(int32)

Here we dont see the statement "ldloc.0" to get the value from the variable instead it just loads the value where it is hard coded in the MSIL.So,obviously there is little performance corresponding to memory usage.But the only issue is that it should have a value before it is compiled.

Example:

using System;
namespace Consoleconst

{
class ConstVar
{
//const int m; Error:\Consoleconst\Class1.cs(7): A const field requires a value to be provided
public ConstVar()
{
// m=10; //Can't initialise in constructor(runtime)
}

}
class Class1
{
const int n=10;//Cannot be accesed with object
[STAThread]
static void Main(string[] args)
{
Console.Write(n);
Consoleconst obj=new Consoleconst();
Console.Read();
}
}
}

Readonly Variables:

If you want a variable that should be set only once but that can be initialised at declaration level(before Compiling) or inside the constructor(Which is evaluated at runtime),then you can go for "readonly".

Example:

using System;
namespace Consolereadonly

{
class readonlyVar
{
public readonly int m;
public readonlyVar()
{
//Assignment after compilation(runtime)
m=10;
}
}
class Class1
{
//Assigned before Compilation
readonly int n=10;
[STAThread]

static void Main(string[] args)
{
Class1 ob1=new Class1();
readonlyVar ob2=new readonlyVar();
Console.WriteLine(ob1.n);
Console.WriteLine(ob2.m);
//ob2.m=20; Error:\Consolereadonly\Class1.cs(23): A readonly field cannot be assigned to (except in a constructor or a variable initializer)
Console.Read();
}
}
}

The difference between this two are:

const:

Can't be static
Value is evaluated at compile time.
Initiailized at declaration only.

readonly:

Can be either instance-level or static.
Value is evaluated at run time.
Can be initialized in declaration or by code in the constructor.

www.codedigest.com

0 Comments:

Post a Comment

<< Home