[Proposal] First-class constructors (constructor method group syntax) #9256
Replies: 3 comments 7 replies
-
From the referenced discussion the syntax was never the problem, it was the behavior given that the compiler is forced to emit a separate lambda instance to wrap the constructor invocation. That would prevent such a feature from working well with, say, event registration/deregistration. |
Beta Was this translation helpful? Give feedback.
-
Just to add a bit of personal context behind this proposal: This isn’t about saving a few keystrokes – it’s about reducing small but constant friction in everyday code. When writing Being able to write |
Beta Was this translation helpful? Give feedback.
-
Adding to prior art Nemerle language where constructor is simply name of the class allowing writing: seq.Select(A). |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
This idea was discussed previously in #674, but no formal proposal was created. I’m proposing a concrete syntax and scope under the name ‘First-Class Constructors.’.
Summary
Enable constructor group conversions via a new syntax:
TypeName.new
orTypeName::new
, allowing constructors to be referenced as first-class functions when their signature matches a delegate.Motivation
In C#, methods can be passed as method groups when their signatures match a delegate type:
But constructors — which are also functions — cannot be referenced in the same way:
This forces developers to write redundant lambda expressions or introduce static factory methods:
We propose a new syntax that makes constructors first-class citizens in delegate assignments and functional contexts:
Design Proposal
Allow constructor group conversions through a constructor reference expression:
The compiler resolves this by finding a constructor in
MyType
whose parameters match the delegate's signature.Matching Rules:
Examples
Benefits
.new
)Class::new
, Kotlin's constructor references)Drawbacks
::
or overloads.
with a keyword)Alternatives
MyType
as a constructor method group directly (e.g.,items.Select(MyType)
), but this is ambiguous and less expressiveOpen Questions
MyType.new
(consistent with static method access) orMyType::new
(explicit and unambiguous)?new
be a contextual keyword in this case?Prior Art
Person::new
::Person
constructor referencesConclusion
This feature would make constructors first-class, unlocking cleaner code and more expressive APIs, especially in LINQ-heavy or functional codebases. It's intuitive, consistent, and already proven in other modern languages. Let's make
new
feel like a first-class citizen in C#.Beta Was this translation helpful? Give feedback.
All reactions