Reply to your doubt regarding static call:
But i heard each static call is
independent of each other as there is
no instance and only static members
are involved. is it so? – Sri Kumar 36
mins ago
You can think there is a 'global' instance of your class, and all static methods are held by this instance.
As in your example, you can create a 'user' instance by calling ClassA myA = new ClassA()
. Meanwhile, there will be a 'global' instance, which is created by the runtime but invisible to you, and static methods reside in this instance. Static methods behavior as instance methods within this 'global' instance.
Amazingly, in C# there is a static constructor, which will be called when the 'global' instance is initialized by the runtime.
You can test this code:
class A
{
static A() {
Console.WriteLine("Creating the global instance of class A....");
}
public static void displayName()
{
Console.WriteLine("myName");
}
public static void displayAge()
{
Console.WriteLine("myAge");
}
}
class B
{
public void Foo()
{
A.displayName();
A.displayAge();
}
}
The output will be:
Creating the global instance of class A....
myName
myAge
Apart from this, static methods have nothing difference from instance methods.
Variables in each static method will have its own scope, and they are independent from one method to another method.