Tuesday, February 10, 2009

Static Variables

Static variable is stored on the heap, regardless of whether it's declared within a reference type or a value type. This heap is separate from the normal garbage collected heap - it's known as a "high frequency heap", and there's one per application domain.

public class A { public static int a = B.b + 1;}
public class B { public static int b = A.a + 1;}
public class MainClass
{
public static void Main()
{
Console.WriteLine("A.a={0}, B.b={1}", A.a, B.b);
// prints A.a=2, B.b=1
}
}

So what happened here is that Console.WriteLine() wanted the value of A.a, to get that it went to the property, now it wanted the value of B.b, this is undefined, so it goes to calculate that value which is A.a+1, so since A.a is by default 0, it uses that value so B.b is given 0+1 = 1 and this 1 is returned as value of B.b to calculate the new value of A.a which now becomes 1+1 = 2.

No comments: