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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With