Monday, March 28, 2011

Static vs Const vs Readonly

Static variables are stored in a special area inside Heap known as High Frequency Heap. Those methods and variables which don't need an instance of a class to be created are defined as being static. Static methods can only call other static methods, or access static properties and fields. Static classes can not inherit from any class and can not be inherited.

Static variables keep their values for the duration of the application domain.

It will survive many browser sessions until you restart the web server (IIS) or until it restarts on its own (when it decides it needs to refresh its used resources).


There is a subtle but important distinction between const and readonly keywords in C#:

Use Const when the value of the variable will stay fixed. const variables are implicitly static and they need to be defined when declared.

Use readonly when the value of the variable changes from user to user but remains constant once initialized at runtime. readonly variables are not implicitly static and can only be initialized once. readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared.

For example:

public class MyClass
{
public readonly double PI = 3.14159;
}

or

public class MyClass
{
public readonly double PI;

public MyClass()
{
PI = 3.14159;
}
}


E.g.: You are writing a storage program in which the memory has a fixed size of 104857600 Bytes. You can define a const variable to denote this as:

private const int _memSize = 104857600 ;

Now, you want the user to enter the amount of memory he needs. Since this number would vary from user to user, but would be constant throughout his use, 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 Storage
{
//this is compile time constant
private const int _totalMemory = 104857600 ;
//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 _memSize ;

public Storage(int memSize)
{}

public AllocateMemory(int memSize)
{
///
///Get the number of cars from the value
///use has entered passed in this constructor
///

_memSize= memSize;
}
}

No comments: