63

Could anyone please tell the difference between these 2 Properties?

DeclaringType and ReflectedType

Consider the code is:

public class TestClass
{
    public static void TestMethod()
    {
        Console.WriteLine("Method in Class", MethodBase.GetCurrentMethod().DeclaringType.Name);
        Console.WriteLine("Method in Class", MethodBase.GetCurrentMethod().ReflectedType.Name);
    }
}

Are these same and Can be used interchangeably?

1
  • In case somebody is wondering why ReflectedType exists: In my opinion, it is a .NET 1.0 design mistake. They probably had a rather specific scenario in mind. I consider it to be better to keep track of the Type yourself instead of adding this hack to reflection objects.
    – usr
    Oct 27, 2020 at 8:03

1 Answer 1

81

They're not exactly the same.

  • DeclaringType returns the type that declares the method.
  • ReflectedType returns the Type object that was used to retrieve the method.

Here's a demo:

MemberInfo m1 = typeof(Base).GetMethod("Method");
MemberInfo m2 = typeof(Derived).GetMethod("Method");

Console.WriteLine(m1.DeclaringType); //Base
Console.WriteLine(m1.ReflectedType); //Base

Console.WriteLine(m2.DeclaringType); //Base
Console.WriteLine(m2.ReflectedType); //Derived

public  class Base
{
    public void Method() {}
}

public class Derived : Base { }

Noticed how the last line printed Derived instead of Base. That's because, even though Method is declared on Base, we used Derived to obtain the MemberInfo object.

Source: MSDN

6
  • 2
    Compare the example from the question, and note that if you make a call to MethodBase.GetCurrentMethod() inside the Method() inside Base, and then calls that method on an instance of Derived (as in new Derived().Method();), you do not get m2 as you may have hoped. You get m1. That is something to be aware of. Oct 16, 2015 at 7:48
  • 2
    In the same light as the previous comment, methods retrieved from a StackFrame (vi StackTrace) through GetMethod also lose out on the 'reflected' bit.. Oct 28, 2016 at 7:44
  • 1
    It might be worth noting that methods overridden in the derived type are considered declared in the derived type, not in the base type. IOW, if Base would override Method, both the DeclaringType and ReflectedType for Derived.Method would be the same.
    – Zev Spitz
    Jul 21, 2020 at 6:19
  • @ZevSpitz Method already is a native member of Base. Base wouldn't override it. That is true if Derived would override it.
    – Suncat2000
    Sep 22, 2020 at 12:37
  • @Suncat2000 That's what I probably meant -- if Derived has an overriding Method.
    – Zev Spitz
    Sep 22, 2020 at 16:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.