Pergunta

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()?

Foi útil?

Solução

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.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top