Monday, January 11, 2010

Static

Static variables are called Class Fields
Static methods are called Class Members
Not static fields are called instance fields or members

What are the things that we can declare as static?
1.data fields
2.member functions
3.properties
4.events

CLASS
A C# class can contain both static and non-static members. When we declare a member with the help of the keyword static, it becomes a static member.

A static member belongs to the class rather than to the objects of the class. Hence static members are also known as class members and non-static members are known as instance members.

In C#, data fields, member functions, properties and events can be declared either as static or non-static. Remember that indexers in C# can't declare as static.

Static classes cannot be instantiated. (I.e. creating an object). If we try to create an object we will get the error, Cannot create an instance of the abstract class or interface 'StaticClassName'

When a class is declared to as static, it is sealed, abstract, and no instance members can be overridden or declared. A static class contains only static members

Since static classes are sealed so they cannot be inherited.

Advantage
No need to create instance.
When to use static class?
Suppose we are using certain methods or properties often we can just call them without creating instance.
It contains only the last updated value. The updated value reflects to all the users.
Static classes can be used when there is no data or behavior in the class that depends on object identity.

static class A
{
static void Foo()
{

A x = null as A; // Cannot declare a variable of static type 'A'
A a; // Cannot declare a variable of static type 'A'
a = new A(); // Cannot create an instance of the static class 'A'

}
}

Static Fields
Static fields can be declared as follows by using the keyword static.
class MyClass
{
public static int x;
public static int y = 20;
}
When we declare a static field inside a class, it can be initialized with a value as shown above.

The static field for a class executes at most once in a given application domain (i.e. when we keep the breakpoint both at a static and non static field and when we refresh the page, the non static field executes but static field didn't). But the value can be changed later in the constructor or anywhere. The last updated value will be maintained there after.

All un-initialized static fields automatically get initialized to their default values when the class is loaded first time.

The C# provides a special type of constructor known as static constructor to initialize the static data members when the class is loaded at first.
// C# static constructor
// Author: rajeshvs@msn.com
using System;
class MyClass
{
public static int x;
public static int y;
static MyClass()
{
x = 100;
Y = 200;
}
}
class MyClient
{
public static void Main()
{
Console.WriteLine("{0},{1},{2}", MyClass.x, MyClass.y);
}
}
Constructor:
Note that static constructor is called when the class is loaded at the first time. However, we can't predict the exact time and order of static constructor execution.

They are called before an instance of the class is created, before a static member is called and before the static constructor of the derived class is called.

Static class can't have instance constructor. (Since we can’t able to instantiate a static class)

A static constructor must be parameter less. (That means there is only one form of static constructor, without any parameters. In other way it is not possible to overload a static constructor).

There is no access modifier require defining a static constructor.

The static constructor for a class executes at most once in a given application domain (i.e. Static constructors are used to perform a particular action that needs performed once only.) The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

1. An instance of the class is created.
2. Any of the static members of the class are referenced.


Static constructor called before the class is referenced for the first time in your program.
It contains only static variables.

Static constructors can't access non-static data members directly.

(A non-static class can have static constructor. When creating instance the static constructor will be called first. Here also the constructor will be called only once till we restart web server.)

Member Functions
Only static members are allowed inside a static class. (I.e. if a class is declared as static all the fields, members should be static.)

We can invoke a static member only through the name of the class.

But a static member function can access only other static members. (I.e. if a member is declared as static all the fields should be static and the method that we are calling from (the caller method) should be static.)
We can’t able to declare a variable as static inside a static method.

An object reference is required for the non-static field, method, or property.

public class foo
{

int x;

static void doSomthingWithX()
{

Console.Write(x.toString);

}
}


Member modifier 'static' must precede the member type and name

void static doSomthingWithX()

Static classes cannot have instance constructors

Cannot declare instance members in a static class

public static partial class StaticClassTest
{

//Static classes cannot have instance constructors
StaticClassTest()
{
}

//cannot declare instance members in a static class
int j = 10;


static int i = 10;

public static int ClassMethod()
{

//The modifier 'static' is not valid for this item
//static int k = 10;

int k = 10;
return i;

return i;
}

//'InstanceMethod': cannot declare instance members in a static class
public int InstanceMethod()
{
return 8;
}

}

The modifier 'static' is not valid for this item
private static void StaticTest()
{
static int i;
i =10;

}

Solution
Whatever we declare inside static method, it is static by default.. So no need to declare a variable as static in static method.

Static Properties
The properties also can be declared as static. The static properties are accessing using the class name. All the rules applicable to a static member are applicable to static properties.
public class PropertyClass
{
private static int x;
public static int X
{
get
{
return x;
}
set
{
x = value;
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
PropertyClass.X = 10; // calls setter
int value = PropertyClass.X; // calls getter
}
Remember that set/get accessor of static property can access only other static members of the class. Also static properties are invoking by using the class name.

Static Members & Inheritance
A derived class can inherit a static member.

But a static member in C# can't be marked as override, virtual or abstract.

However it is possible to hide a base class static method in a derived class by using the keyword new.
public class BaseClassTest
{
public static int i = 10;
public static int get()
{
return i;
}
}

public class ChildClassTest : BaseClassTest
{
public static int j;

//ChildClassTest()
//{
// //cannot be accessed with an instance reference; qualify it with a type name instead
// j = base.i;
//}

//static ChildClassTest()
//{
// //Keyword 'base' is not available in a static method
// j = base.i;
//}

}
class Final : ChildClassTest
{
int p = ChildClassTest.i;
int o = ChildClassTest.get();
int r = ChildClassTest.j;
}

class tester
{
int p = Final.i;
int o = Final.get();
int r = Final.j;
}
Finally remember that it is not possible to use this to reference static methods.
Static Indexers
In C# there is no concept of static indexers, even though static properties are there.
http://www.c-sharpcorner.com/UploadFile/rajeshvs/PropertiesInCS11122005001040AM/PropertiesInCS.aspx

http://www.csharphelp.com/2006/04/c-static-members/

No comments: