Reputation: 710
Say I have an abstract superclass, A
, which is defined as:
public abstract class A {
protected string a1;
protected int a2;
protected char a3;
public A(string a1, int a2, char a3) {
this.a1 = a1;
this.a2 = a2;
this.a3 = a3;
}
}
I then have x classes that inherit from A -- each using the same constructor -- but each have their own methods which use a1, a2, and a3 in their own unique ways. Despite the constructors being the same, from what I understand I'd have to re-define the number and type of arguments in each subclass like so:
public sub(string a1, int a2, char a3) : base(a1, a2, a3) {}
This could be a pain if I need to change the type of arguments, because I'd need to tweak all 11 classes. If I'm using good inheritance practices, in most cases all classes should be affected anyway if I modify the parameters of A
's constructor, but there are some instances where this isn't true. For instance, if I change a parameter from type Vehicle
to Car
. Car
is a subclass of Vehicle
, so it has all of Vehicle
's API members, and none of the classes would need changing, aside from their constructor.
Is there any way to do something along the lines of:
public sub {
public sub(...) : base(...) {}
}
so that there's no need to change all 10 subclass constructor definitions when an argument type changes?
Upvotes: 0
Views: 157
Reputation: 100555
No, there is no syntactic sugar for it.
You can wrap all parameters in a class so changes to parameters will not impact all types, but you can easily miss handling of newly added parameters:
class ConstructorParams
{
public int a {get;set;}
}
...
public Base( ConstructorParams p) {...}
...
public Sub(ConstructorParams p) : Base(p) {}
Note that using refactoring tools in VS (and external like R#) makes changes to method/constructor's arguments mostly automatic - so may be good idea to try those first before packing all parameters into single class.
Upvotes: 2