I'm trying out the new record features using latest .Net5
public record Rec {
public string Name;
public int Id;
//public Rec(string name, int id) => (Name, Id) = (name, id);
}
I get
warning CS8618: Non-nullable field 'Name' is uninitialized. Consider declaring the field as nullable.
So a constructor is not generated whereas I understood that is a feature of records ?
and why not the same warning for Id
?
If I unremark the ctor above the warning goes away (which makes sense)
Also if I do instead:
public record Rec(string Name, int Id);
There are no warnings.
EDIT
so it seems the two forms of creating a record (longer vs shorter syntax) are different, the short version makes the fields public and also adds a ctor whereas the first one does not. I can't find a reference to that.
So a constructor is not generated whereas I understood that is a feature of records ?
According to the documentation: A Primary Constructor is synthesized for all Value Parameters of the Parameter List for the Positional Record.
Your first example doesn't have a Parameter List and thus doesn't have Value Parameters, therefore it is not a Positional Record, and therefore it doesn't have a Primary Constructor.
and why not the same warning for
Id
?
Because the default constructor for int
is, and always has been, 0
, not null
. This isn't really specific to record
s, this has always been the case, since before C# 1.0.