Proposal: primary constructors on records allow for object initializer syntax #8052
Replies: 2 comments 4 replies
-
Terse does not always improve legibility. In this case, your proposal is violating expectations on behavior for constructors and object initializer syntax. A constructor specifies required data while object initializer syntax allows for further specification of the instance at initialization and only members explicitly marked as You can see that with this sample snippet: // no error about fizz not being set.
var sample = new Sample(foo: "foo") { Bar = "bar" };
// error because bar is not set but is required
var sample = new Sample(foo: "foo") { Fizz = 3 };
public sealed class Sample(string foo)
{
public string Foo { get; set; } = foo;
public required string Bar { get; set; }
public int Fizz { get; init; }
} |
Beta Was this translation helpful? Give feedback.
-
You could use a source generator to emit a partial type for the record containing a parameterless constructor. But it's intentional that a positional record is required to be created through the primary constructor. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
Update c# so that all records declared via primary constructor syntax can be instantiated either via constructor syntax or object initializer syntax. All constructor parameters in the record declaration function as
required
properties such that the consumer must provide them when opting for object initializer syntax.Example
Record declaration:
Initialization via object initializer syntax:
-- or --
Initialization via constructor:
This would fail to compile because
TenantId
is a required property:Workaround
We can achieve roughly equivalent functionality from the consumer's perspective via a much more verbose record declaration:
Background and Motivation
Facilitate terser and more readable record declarations for instances where we want to give a consumer the choice of object initializer or constructor syntax.
Beta Was this translation helpful? Give feedback.
All reactions