Required constructors in derived abstract classes #9380
-
How feasible is it to not require abstract classes derived from another class to (re)implement a trivial non-default constructor? This would be similar, conceptually, to how abstract properties are handled. Consider the following: public abstract class SomeClassA // I suppose it doesn't really matter if this is abstract
{
public SomeClassA(int x, int y, int z)
{
}
}
public abstract class SomeClassB : SomeClassA // being abstract matters here
{
// this produces: error CS7036: There is no argument given that corresponds to the required parameter 'x' of 'SomeClassA.SomeClassA(int, int, int)' or if there are multiple base constructors then the error is about there being no parameterless constructor.
}
public abstract class SomeClassC : SomeClassA // being abstract matters here
{
public SomeClassC(int x, int y, int z) : base(x, y, z) // this is required even though the class is abstract and cannot be constructed
{
}
} So But any concrete (or currently abstract) class that inherits from Two approaches I could think of are:
I don't know enough to know which is ideal. Option 1 certainly seems possible, since the compiler already "skips" classes to get things like abstract properties that are required, and I guess default constructors. But Option 2 might be preferrable for the explicit IL and/or for backwards compatibility with things that might expect the IL to be there. Obviously, if the developer adds a constructor then the compiler would just do what it currently does. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 14 replies
-
Because every derived type must call its base type's constructor, not other ancestor type. The constructor of abstract class logically initializes every state at this level. For example, if you have a field with default value, it's initialized in the constructor: public abstract class Ancestor
{
public Ancestor(int unused) {}
}
public abstract class Base : Ancestor
{
private int state = 123;
public Base(int unused) : base(unused) {}
} Here the constructor of Properties are methods exposed to callers, not state kept by implementers. |
Beta Was this translation helpful? Give feedback.
We're not comfortable synthesizing public surface area like this for a type. You could always write your own source generator to produce these for you if you want.