I tried just a simple record:
#nullable enable
public record Product
{
public readonly string Name;
public readonly int CategoryId;
public readonly string Phone;
public readonly Address Address;
public readonly Manager Manager;
}
I get warnings:
Non-nullable property 'Name' is uninitialized. Consider declaring the property as nullable.
(same for all fields except CategoryId)
Basically, if I understand correctly, a constructor accepting and setting all fields is not auto-generated by the compiler and (when using #nullable enable) I have to write it myself, i.e.:
public Product(string Name, int CategoryId, string Phone, Address Address, Manager Manager) {
this.Name=Name;
this.CategoryId=CategoryId;
...
}
My question is, is this correct? I am very surprised by this as I thought the whole point was to make creating records like that really simple, and having to write/maintain the constructor is very tedious, especially on big records that change often. Or am I missing something here?
You seem to be expecting the auto-generated Primary Constructor, but it is auto-generated (and in general you get all the record benefits) when you utilize the record parameters in the record type declaration, which are automatically mapped to public get and init properties and automatically initialized from the primary constructor, thus eliminating the NRT warning.
Which means that you get all record type sugar by basically using the normal constructor syntax with added record keyword:
public record Product(string Name, int CategoryId, string Phone, Address Address, Manager Manager) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With