Static Class, Static Variable, Static Method, Static Constructor
Static classes and static members are used to create data and functions that can access without creating instance of the class.
Static Classes
Static class only contains static members. We cannot instantiate static class object. This means new keyword is not used to instantiate class. CLR is responsible to load static class.
Feature of static class are:
- They are only contains static members.
- They cannot be instantiated.
- They are sealed.
- They cannot contains Instance Constructor. Instance constructors are used to create and initialize instances.
The complier will guarantee that instances of static class cannot be created. Static class is sealed and therefore it cannot be inherit. The static class can have static constructor.
Use a static class as a unit of organization for methods not associated with particular objects.
Static Methods
A static method, filed, property or event is directly called without instantiate class object. Only one copy of static fields and events exists in memory and static methods or static properties can only access static fields or static events. Static method can be overloaded but not overridden.
Static members are initialized before the static member is accessed from first time.
Static Constructor
A class or structure can have static constructor which is used to initialized static members. This constructor called at most once. An instance constructors always run after static constructor.
namespace staticApps
{
static class democlass
{
static int num;
static int num1;
static democlass()
{
num = 10;
num1 = 20;
}
public static int sum()
{
return num + num1;
}
}
}
Static Variable and Garbage Collector
Garbage Collector receives list of root object references. These root consist of global/static variables, variable on the stack and anything managed to heap that is pointed to by a memory address in the CPU should be preserved. Object is not garbage collected if it is static variable. Think before declaring static variable it not closed and never released by GC so it may effects the performance of code.
If two threads called static variable at same time it then both are assigned same value. In the method IncrementedNumber() I am assigning num1 to cnt and increment num1 after that. If two or more threads use IncrementedNumber() at same time it will return same value which may we wrong. To make sure only one thread can access piece of code one time then we need to place that piece of code in lock() block.
static class democlass
{
static int num;
static int num1;
static democlass()
{
num = 10;
num1 = 20;
}
public static int sum()
{
return num + num1;
}
public static int IncrementedNumber()
{
lock(typeof(democlass))
{
int cnt;
cnt = num;
num++;
return cnt;
}
}
}
In this all thread wait in queue to execute the code in lock() block. So this is good practice to as small as possible piece of code in lock block.
| Date:- 7-Jan, 2010 |