Remove the need for parenthesis on a parameterless primary constructor. #7910
-
Currently, to leverage primary constructors, parenthesis are required for the defining object, regardless of whether parameters are defined or not. Take the following simple example: public abstract class Component(string name, string description)
{
public string Name { get; set; } = name;
public string Description { get; set; } = description;
}
public sealed FooComponent
: Component(
name: nameof(FooComponent),
description: "A sample component for...")
{
...
} This results in a compiler error:
Adjusting to satisfy results in: public sealed FooComponent()
: Component(
name: nameof(FooComponent),
description: "A sample component for...")
{
...
} I understand it's only two characters, but why is it needed if we can already determine that the base type constructor call syntax is being used? ClarificationMy question is more geared towards the idea that the parentheses are required to use base-type constructor call syntax. Is it commonly known (or are there public discussions on) why that requirement is imposed? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 8 replies
-
Because you are still defining a primary constructor, albeit one that is parameterless. public abstract class Component(string name, string description)
{
public string Name { get; set; } = name;
public string Description { get; set; } = description;
}
// with primary constructor
public sealed class FooComponent() : Component(
name: nameof(FooComponent),
description: "A sample component for...")
{
}
// without primary constructor
public sealed class BarComponent : Component
{
public BarComponent() : base(
name: nameof(FooComponent),
description: "A sample component for...") { }
} |
Beta Was this translation helpful? Give feedback.
Probably because it wasn't considered that an empty parameterless constructor could be inferred to behave like a primary constructor. It's likely less an intentionally imposed limitation than the a feature of primary constructors that requires primary constructors. The question would be whether or not it's worth revisiting at this point to avoid two characters. Probably not, unless there are other reasons to revisit constructors in which case it could get bundled in if the language team considered it worthwhile.