Difference between DeclaringType and ReflectedType
C#.Net 4.0C# 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 theType
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