Dandy
Dandy

Reputation: 1481

Instantiating an Inheritance Object Class with Parent Properties

I am using an SDK method that returns a model native to that SDK.

In my code, I want to add some extra properties to my base class.

Example:

public class BaseClass {
    public string Prop1 {get; set;}
} 

public class ChildClass : BaseClass {
   public string Prop2 { get; set; }
}


BaseeClass baseClassObject = SDK.Method1();

ChildClass child = new ChildClass(); <- Populate this with baseClassOjbect properties. 

Is inheritance the best to do this/most efficient? If so, how do I instantiate the child object with the properties of the base class?

I could create a new class without inheritance with the properties of the BaseClass and then some extra properties (without using inheritance) but I just wonder if there's a 'better' use of C# for achieving this?

Upvotes: 2

Views: 46

Answers (1)

Nkosi
Nkosi

Reputation: 247058

Consider passing the base object to the child and copy the desired properties

public class BaseClass {
    public string Prop1 {get; set;}
} 

public class ChildClass : BaseClass {

    public ChildClass() : base() {}

    public ChildClass(BaseClass baseClassObject) : base() {
        this.Prop1 = baseClassObject.Prop1;
    }

    public string Prop2 { get; set; }
}

So now the child class can be initialized like this

BaseeClass baseClassObject = SDK.Method1();

ChildClass child = new ChildClass(baseClassObject) {
                        Prop2 = "Some value"
                   };

and get populated with baseClassOjbect properties.

Upvotes: 4

Related Questions