Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, access child properties from parent reference?

Tags:

c#

inheritance

public void GetProps(Parent p){

   // want to access lots of child properties here
   string childProp1 = p.prop1;
   bool childProp2 = p.prop2;
   bool childProp3 = p.prop3;

}

However compiler complains that

"Parent does not contain definition prop1"

The function would take in different subtypes of Class Parent.

All the subclasses have this

public override string prop1 { get; set; }

Is there a way of accomplishing this?

EDIT: To make the question clearer

I current have a giant if-elseif where i do something like

if(p is Child0){
      Child0 ch = p as Child0; 

       // want to access lots of child properties here
       string childProp1 = ch.prop1;
       bool childProp2 = ch.prop2;
       bool childProp3 = ch.prop3;

}else if(p is Child1){
      Child1 ch = p as Child1; 

       // want to access lots of child properties here
       string childProp1 = ch.prop1;
       bool childProp2 = ch.prop2;
       bool childProp3 = ch.prop3;

}else if(...// and many more 

Now I wanted to remove all the redundant code and make one function that can handle all this.

like image 437
Kevin Boyd Avatar asked Dec 17 '22 00:12

Kevin Boyd


1 Answers

If all child classes need to have the properties (but with different implementations), you should declare them as abstract properties in the base class (Parent), then implement them in the child classes.

If some derived classes won't have those properties, then what would you expect your current GetProps to do?

EDIT: If you're using C# 4 and you definitely can't get a better class design (where the parent class declares the property) you could use dynamic typing:

public void GetProps(Parent p) {
    dynamic d = p;
    string childProp1 = d.prop1;
    bool childProp2 = d.prop2;
    bool childProp3 = d.prop3;
    // ...    
}

I'd treat this as a last resort though...

like image 189
Jon Skeet Avatar answered Feb 10 '23 16:02

Jon Skeet