I am not sure if this is a limitation of the language, but I am having difficulty creating records using the shorthand construction way of declaring them when using inheritence.
Assume you have two classes:
public record ParentRecord(Guid Id, string Value);
public record ChildRecord(Guid Id, string Value, string Extra) : ParentRecord(Id, Value);
In the C# extension, this doesn’t flag any problems. But as soon as i try to build, i get:
Init-only property or indexer ‘ChildRecord.Id’ can only be assigned in an object initializer, or on ‘this’ or ‘base’ in an instance constructor or an ‘init’ accessor.
It seems like this approach should be considered within the scope of ‘init’, but it isn’t.
The following (using the base method call) builds okay.
public record ChildRecord : ParentRecord {
public ChildRecord(Guid Id, string Value, string extra) : base(Id, Value) { }
}
Does anybody have a way to simplify record decleration to the above to call base() without opening up the constructor body, or do i have to just take the long hand approach?
Works for me on dotnetfiddle: https://dotnetfiddle.net/o25bfa
Can you create a minimal, reproducible example code/program we can copy paste? https://stackoverflow.com/help/minimal-reproducible-example
Are you using the latest version of Visual Studio and targeting .NET 5?
I don’t think there is a dedicated syntax to shorten it.
That being said, it really makes me wonder why you’re even using inheritance here at all instead of composition?
On a personal note, I think that subtyping of record types is iffy at best… I see them through a lens of immutable data bags, similar to records in functional languages, instead of ‘entities with behavior’ from object-oriented languages.
C# devs
null reference exceptions