views:

30

answers:

2
// 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")
    {            
    }
}
+2  A: 

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.

Mark Cidade
Thanks. Re b) - because in my example the string being passed is a literal, could it be found in the IL?
zadam
Yes, you're correct. I updated my answer to reflect that, so to speak.
Mark Cidade
A: 

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.

zadam