Friday, May 29, 2009

Watch out for GetType()

I just finished reading an interesting post by James Hart about the differences between this.GetType() and typeof(MyClass).
The point that he makes is the fact that this.GetType() will return the type of the current implementation, not where it was implemented. For example if you have MyControl that uses this.GetType(),and then create MySpecializedControl that inherits form MyControl and then expect to get the type of MyControl you will fail. Why? because when you this.GetType() will return the type of the current implementation (MySpecializedControl) even when residing in a class further down the inheritance chain.
If you instead use typeof(MyControl) the result will always be the same. And as James mentions typeof is calculated at compile time and not at runtime using Reflection.