Will GetType() return the most derived type when called from the base class?

C#InheritancePolymorphism

C# Problem Overview


Will GetType() return the most derived type when called from the base class?

Example:

public abstract class A
{
    private Type GetInfo()
    {
         return System.Attribute.GetCustomAttributes(this.GetType());
    }
}

public class B : A
{
   //Fields here have some custom attributes added to them
}

Or should I just make an abstract method that the derived classes will have to implement like the following?

public abstract class A
{
    protected abstract Type GetSubType();

    private Type GetInfo()
    {
         return System.Attribute.GetCustomAttributes(GetSubType());
    }
}

public class B : A
{
   //Fields here have some custom attributes added to them

   protected Type GetSubType()
   {
       return GetType();
   }
}

C# Solutions


Solution 1 - C#

GetType() will return the actual, instantiated type. In your case, if you call GetType() on an instance of B, it will return typeof(B), even if the variable in question is declared as a reference to an A.

There is no reason for your GetSubType() method.

Solution 2 - C#

GetType always returns the type that was actually instantiated. i.e. the most derived type. This means your GetSubType behaves just like GetType itself and thus is unnecessary.

To statically get the type information of some type you can use typeof(MyClass).

Your code has a mistake though: System.Attribute.GetCustomAttributes returns Attribute[] not Type.

Solution 3 - C#

GetType always returns the actual type.

The reason for it is deep in the .NET framework and CLR, as the JIT and CLR use the .GetType method to create a Type object in memory that holds the information on the object, and all access to the object and compilation are via this Type instance.

For more information, take a look in the book "CLR via C#" from Microsoft Press.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatthew CoxView Question on Stackoverflow
Solution 1 - C#Reed CopseyView Answer on Stackoverflow
Solution 2 - C#CodesInChaosView Answer on Stackoverflow
Solution 3 - C#yoel halbView Answer on Stackoverflow