Eric98118
Eric98118

Reputation: 409

Is there a way to leverage inheritance when including a parameter of the base class in a constructor?

From what I've read, there doesn't appear to be a good way to convert a class a base class to an inheriting class.

Following the answer in this question, I've gone ahead and just created a constructor that takes an instance of the base class as a parameter.

The constructor looks like this:

public DerivedClass(BaseClass base) {
    this.Id = base.Id;
    this.Foo = base.Foo;
    // ..
    this.NewProperty = SomeNewValue;
}

etc. This also means that if the base class gets a new property, the constructor in the derived class also needs to be modified in order to copy that property.

Is there a way to leverage the fact that the derived class inherits from the base class to make this constructor less fragile?

Upvotes: 1

Views: 237

Answers (2)

slugster
slugster

Reputation: 49974

It seems you haven't fully grasped inheritance and you've over-thought what you need to do.

I've gone ahead and just created a constructor that takes an instance of the base class as a parameter.

You don't need to do this when extending (inheriting from) a base class, you only do this when wrapping a class.

Is there a way to leverage the fact that the derived class inherits from the base class to make this constructor less fragile?

Yes: use constructor overloading. Given this base class:

public class MyBase
{
    public virtual string Name { get; set;}
}

you could do this:

public class MyExtendedClass : MyBase 
{
    public MyExtendedClass(string name)
    {
        Name = name;
    }
}

but better still is to leverage constructor overloading like this, where constructor parameters are passed through to the base class constructor:

public class MyBase
{

    public MyBase(string name)
    {
        Name = name;
    }

    public virtual string Name { get; set;}
}

public class MyExtendedClass : MyBase 
{
    public MyExtendedClass(string name) : base (name) {   }
}

You would tend to pass in values on the constructor for properties that you want to be immutable. For the others, you can take advantage of inline initialization:

var myNewClass = new MyExtendedClass() { Name = "blah" };

Upvotes: 4

Martin
Martin

Reputation: 16423

Could you not add a protected constructor to the base class that carries out the assignments and then just pass the base class down to it as a parameter:

protected BaseClass(BaseClass source)
{
    this.Id = source.Id;
    this.Foo = source.Foo;
    ...
}

Thereby keeping the code to duplicate the base class in the base class itself?

Upvotes: 0

Related Questions