Tutorial :Why is Object.GetType() a method instead of a property?



Question:

From a design perspective, I wonder why the .NET creators chose System.Object.GetType() instead of a System.Object.Type read-only property.

Is it just a (very minor) design flaw or is there rationale behind there? Any lights welcome.


Solution:1

If you look at the GetType() declaration in Reflector you'll find this:

[MethodImplAttribute(MethodImplOptions.InternalCall)]  public extern Type GetType();   

What that combination of attribute and extern means is that this method is actually implemented in unmanaged code inside the .NET runtime itself. The GUID question in this article goes into further details. They obviously did this for performance reasons after determining that figuring out the Type would be faster if handled at a lower level.

This leads to two reasons not to implement the GetType method as a property. Firstly you can't define properties extern as you can with methods, so it would need to be handled in native .NET code. Secondly even if you could define them as extern, performing an unsafe, unmanaged call from inside a property would definitely break the guidelines for property usage since it's much harder to guarantee that there are no side effects.


Solution:2

The guidelines say that a property should represent a state of the object, it should not be expensive performance wise, and it should not have side effects apart from computing/setting that state. My guess is GetType() does not respect these rules so they made it a method.

GetType() is a slightly expensive operation. If it were a property it would encourage uses like

DoStuff(obj.Type);  ....  DoStuff(obj.Type);  

etc.

instead of

Type type = obj.GetType();  DoStuff(type);  ....  DoStuff(type);   

and that would be not so optimal. So they made it a method to suggest that it should be called sparingly.


Solution:3

As I understand it, it is in general considered good practice for internal fields or values which are trivial to calculate to be exposed using a property, and other values, which may require more time or other resources to calculate, to be exposed using a method.


Solution:4

Only Microsoft can answer that question, but I think it's because several classes in the .NET Framework create their own overloaded versions of GetType() with extra parameters. If it would have been a property, they couldn't use the same name (because properties don't have parameters).

Just my thoughts on the subject.


Solution:5

A bit late reply but crashed into the question while trying to find something related.

It is possible for GetType to throw an exception. Framework guidelines state that properties should not throw exceptions. This is one more reason why it should be a method instead of property.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »