Record type with multiple constructors

Simply add the constructor you want like this: record Rank(int level, string description); record Manager(string FirstName, Rank Rank) { public Manager() : this(“”, new Rank(0, “Entry”)) { } // public Manager(string FirstName, Rank Rank) is auto generated }

How do I target attributes for a record class?

To target the various parts of the expanded class, use the appropriate attribute target. For instance: // Target the property, use `property` record Person(string FirstName, string LastName, [property: JsonIgnore] int Age); // Target the backing field of the property, use `field` record Person(string FirstName, string LastName, [field: JsonIgnore] int Age); // Target the constructor parameter, …

Read more

C# 9 records validation

I’m late to the party, but this might still help someone… There’s actually a simple solution (but please read the warning below before using it). Define a base record type like this: public abstract record RecordWithValidation { protected RecordWithValidation() { Validate(); } protected virtual void Validate() { } } And make your actual record inherit …

Read more

Custom Equality check for C# 9 records

Per the C#9 record proposal, the following should compile, even if not very useful without actual implementations.. // No explicit IEquatable<R> – this is synthesized! public sealed record SimpleVo { // Not virtual, as SimpleVo (R) is sealed. // Accepts SimpleVo? (R?), and not SimpleVo (R), as argument. public bool Equals(SimpleVo? other) => throw new …

Read more

Testing C# 9.0 in VS2019 – CS0518 IsExternalInit is not defined or imported … How do I define/import it?

This is a bug in the current preview and the latest master branch (June 27). A simple record in sharplab.io creates the same error. Just add the missing type somewhere in your project using System.ComponentModel; namespace System.Runtime.CompilerServices { [EditorBrowsable(EditorBrowsableState.Never)] internal class IsExternalInit{} } Records and init will work without problem. Only LinqPad 6 seems to …

Read more