Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

clr

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.

like image 310
Serge Wautier Avatar asked Jun 11 '09 10:06

Serge Wautier


2 Answers

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.

like image 94
Martin Harris Avatar answered Sep 30 '22 15:09

Martin Harris


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.

like image 45
Adrian Zanescu Avatar answered Sep 30 '22 16:09

Adrian Zanescu