Why is an explicit `this` constructor initializer required in records with a primary constructor?

This is because primary constructor parameters are a little bit special – they are in scope throughout initialization of the record. Guess what the following program prints: System.Console.WriteLine(new Foo(Bar: 42).Baz); public record Foo(int Bar) { public int Bar => 41; public int Baz = Bar; } 41 or 42? And the answer is… drumroll please… … Read more

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