Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between DeclaringType and ReflectedType

Tags:

c#

.net-4.0

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?

like image 464
Khurram Hassan Avatar asked Feb 19 '14 14:02

Khurram Hassan


1 Answers

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

like image 119
dcastro Avatar answered Sep 28 '22 15:09

dcastro