[Proposal] Multiple primary constructors. #9730
-
|
Currently, in C#, classes can have only one primary constructor.
Example of syntax/variant 1:class Foo
(int x, int y) : BaseFoo(a, b),
(Point point) : BaseFoo(point)
{
// methods ...
}Behave like just multiple regular constructors without ctor-method body. class Foo : BaseFoo
{
public Foo(Point point) : base(point) { }
public Foo(int x, int y) : base(x, y) { }
}Example of syntax/variant 2:class Foo
(int x, int y) : BaseFoo(a, b) | (Point point) : BaseFoo(point)
{
// methods ...
}Variables from both constructors and class Foo : BaseFoo
{
int x, y;
Point point;
public Foo(int x, int y){
x = x;
y = y;
base(x, y);
}
public Foo(Point point){
point = point;
base(point);
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 6 replies
-
|
What advantage does having multiple primary constructors bring over having 2 regular constructors? You can already separate constructors from methods easily enough by just maintaining order in your definitions. The likelihood that adding a new primary constructor would not change the existing code is extremely low, as it would invalidate any constructor parameter captures in the rest of the body. In general, the concept of "multiple primary" is somewhat conflicting. |
Beta Was this translation helpful? Give feedback.
-
|
The scoping doesn't make sense. How can you have a You can already declare secondary constructors which call the primary constructor, that is the correct way to do this: class Foo(int x, int y) {
Foo(Point pt) : this(pt.X, pt.Y) { }
// x and y are in scope here, pt is not
} |
Beta Was this translation helpful? Give feedback.
-
class Foo
(int x, int y) : BaseFoo(a, b),
(Point point) : BaseFoo(point)
{
// methods ...
}I don't understand the semantics here. How would methods know if they could access x, y, or point? Some 'Foos' would be instantiated with an x and y and no point, and vice versa. No methods would be safe to write. |
Beta Was this translation helpful? Give feedback.
Why are you trying to use primary constructors here? They are not intended to be shorthand for regular constructors, their entire point is in capturing the parameter values across the scope of the entire type. Attempting to splat all constructors parameters as captures would subvert that and lead to an awful developer experience. This proposal solves no problems but creates some really bad ones.