Saturday, September 04, 2004

Whats wrong in using Static Methods

The question here is that why can't we use static methods in our class instead of making a Singleton pattern. I found the solution and explaination on web. View the code below:

public class A {
public static string staticVariableCopiedFromB = B.staticVariable;
public static string staticVariable = "This is a string defined in A";
}

public class B {
public static string staticVariableCopiedFromA = A.staticVariable;
public static string staticVariable = "This is a string defined in B";
}

public class Test {
static void Main(string[] args)
Console.WriteLine(A.staticVariableCopiedFromB);
Console.WriteLine(B.staticVariableCopiedFromA);
}

Now just try to dry the program. Our common sense suggest that the output of this program should be like this:
This is a string defined in B
This is a string defined in A

Unfortunately this is not the case and you will only see the following output:
This is a string defined in B

Why is that so?
Lets see whats happening in Main().
1) A.staticVariableCopiedFromB: This goes to class A and notices that A.staticVariableCopiedFromB depends upon B.staticVariable, so it goes to B.staticVariable get the string "This is a string defined in B" and assigned to A.staticVariableCopiedFromB.

2) Next is B.staticVariableCopiedFromA: It goes to class B and see that B.staticVariableCopiedFromA depends upon A.staticVariable but then realizes that it was never Initiazed and hence assigns "null" to B.staticVariableCopiedFromA and output nothing.

The problem with static methods is complex Initializations and you never know who can change what and its very hard to find such problems.

Also you cannot override static methods. On the other hand you can Inherit from the Singleton class.


No comments: