Saturday, August 30, 2008

Deconstructing the System.Type class

I always knew that Type class was special. So lets spend some time on understanding it.

1. On looking at its documentation, what confused me a bit was that the class is declared as an abstract class.

a. So how does the typeof operator creates an instance of the class. Well it actually creates instance of System.RuntimeType, which itself is derived from System.Type

2. Another interesting fact to note is that Type object that represents a type is unique; that is, two Type object references refer to the same object if and only if they represent the same type. This allows for comparison of Type objects using reference equality. In other words, for any type, there is only one instance of Type per application domain.

a. Not to worry, the Type class is thread safe.



Type type1 = typeof(A);
Type type2 = typeof(B);

Type type3 = type1.GetType(); // System.RuntimeType
Type type4 = type2.GetType(); // System.RuntimeType

bool b = type3 == type4; // Returns true,showing for both A and B,there is 1 instance





3. In multithreading scenarios, do not lock Type objects in order to synchronize access to static data. Other code, over which you have no control, might also lock your class type. This might result in a deadlock. Instead, synchronize access to static data by locking a private static object. This means never write the most commonly used

lock (typeof (A) ){
}

No comments: