views:

238

answers:

1

I have a class (Descendant1) that inherits from a base class (BaseClass). An instance of a descendant class is passed into a method that takes BaseClass as a parameter. Then using reflection, it calls a property on the object.

public class BaseClass { }

public class Descendant1 : BaseClass
{
    public string Test1 { get { return "test1"; } }
}


public class Processor
{
    public string Process(BaseClass bc, string propertyName)
    {
        PropertyInfo property = typeof(BaseClass).GetProperty(propertyName);
        return (string)property.GetValue(bc, null); 
    } 
}

My question is this. In the Process method, is it possible to figure out what the object really is (Descendant1), then declare an object (perhaps using Reflection) of that type and cast the BaseClass parameter to it, then do reflection acrobatics on it?

Thanks.

+6  A: 

i am not sure if i understand your question but maybe you are thinking of something like this:

        public string Process(BaseClass bc, string propertyName)
        {
            PropertyInfo property =  bc.GetType().GetProperty(propertyName);
            return (string)property.GetValue(bc, null);
        }

bc.GetType() gets real type of bc (when you pass Descendant1 it will be Descendant1 not BaseClass).

empi
That is exactly what I meant. Thanks a lot.
AngryHacker