3

While attempting to compare two dlls for API changes, a co-worker noticed that some classes had two GetType() methods.

Upon deeper inspection, it turns out that System.Exception shadows GetType():

// this method is required so Object.GetType is not made virtual by the compiler
public new Type GetType() 
{
  return base.GetType(); 
}

I see that System.Exception implements _Exception, but I don't see a reason why GetType has to be explicitly shadowed as it wouldn't be virtual anyways.

So why does System.Exception shadow GetType()?

zastrowm
  • 8,017
  • 3
  • 43
  • 63

2 Answers2

1

I'm not sure if it has anything to do with COM as mentioned by shriek, but it definitely does have to do with not making Object.GetType() virtual.

The second link in shriek's answer alluded to it, but this answer to another question makes it more clear:

The CLR requires that all methods that implement an interface method must be virtual (Ecma 335 Partition II Section 12.1).

  • If the method in the base class is not virtual, but in the same assembly, the sneaky compiler actually makes it virtual and final.

If System.Exception didn't shadow GetType(), the GetType() implementation for Object would automatically be converted to a virtual method by the compiler.

Community
  • 1
  • 1
zastrowm
  • 8,017
  • 3
  • 43
  • 63
  • Yep - it was because of that post that I found the other StackOverflow question. – zastrowm May 27 '13 at 17:09
  • Why is this a problem? – IS4 Mar 07 '15 at 21:51
  • I assume for performance reasons. `GetType()` will only ever have one implemented (provided by the CLR), so why make add a new entry in the btable at all and why cause the overhead of a virtual method. – zastrowm Mar 09 '15 at 14:54
0

Look here and in the comments here for the "long" answer.

In short, System.Exception implements the System.Runtime.InteropServices._Exception interface which also has a GetType-Method and thus has to new-implement the GetType-Method.

shriek
  • 5,157
  • 2
  • 36
  • 42
  • 1
    I'm not exactly sure why it has to `new` it though. You can create a class that implements `_Exception` without shadowing GetType(). Nor does the CLR seem to automatically implement it, as mentioned in the second link. – zastrowm May 23 '13 at 18:48
  • http://stackoverflow.com/a/3477588/1260405 this post might answer the question. Also, System.Type is done like this as well and also implements a com interface. – shriek May 23 '13 at 20:09