Difference between DeclaringType and ReflectedType

C#.Net 4.0

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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

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
QuestionKhurram HassanView Question on Stackoverflow
Solution 1 - C#dcastroView Answer on Stackoverflow