Tutorial :Use reflection to determine which base class constructor is called


Using reflection on the type DerivedClassB can we determine:
a) that it uses the base class ctor that takes a string param
b) the actual value that it passes?

public class BaseClass  {      public BaseClass()      {                  }        public BaseClass(string someParameter)      {                  }  }    public class DerivedClassA : BaseClass  {      public DerivedClassA()      {                  }  }    public class DerivedClassB : BaseClass  {      public DerivedClassB(): base("canWeFindThis")      {                  }  }  


a) Yes. Technically, you can find out which other constructors are called, if you read the information from ConstructorInfo.GetMethodBody() but without a helper library like Mono.Cecil, you'd have to decode the IL from a byte array.

b) In your case, yes but generally no. Reflection can only be used to reflect on static data, not runtime dynamic state, so you wouldn't be able to use it to know which values were passed as parameter to a constructor unless it was specified as a literal, like you have, in which case you can use the same technique above with ConstructorInfo.GetMethodBody() or Mono.Cecil.


As a follow-up to this, I realized that the value being passed to the base class actually gets exposed through a property on the base class.

So for my scenario I just instantiated the type and then interrogated the value of the property to find out what has actually been passed in the constructor. HTH.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »