0 0
Read Time:1 Minute, 17 Second
An init-only setter in a property declaration uses the init keyword instead of the set keyword:
class Foo { public int ID { get; init; } }

This behaves like a read-only property, except that it can also be set via an object initializer:

var foo = new Foo { ID = 123 };

This makes it possible to create immutable (read-only) types that can be populated via an object initializer instead of a constructor, and helps to avoid the antipattern of constructors that accept a large number of optional parameters. Init-only setters also allow for nondestructive mutation when used in records.

Records
A record is a special kind of class that’s designed to work well with immutable data. Its most special feature is that it supports nondestructive mutation via a new keyword (with):

Point p1 = new Point (2, 3);
Point p2 = p1 with { Y = 4 }; // p2 is a copy of p1, but with Y set to 4
Console.WriteLine (p2); // Point { X = 2, Y = 4 }
record Point
{
 public Point (double x, double y) => (X, Y) = (x, y);
 public double X { get; init; }
 public double Y { get; init; } 
}

In simple cases, a record can also eliminate the boilerplate code of defining properties and writing a constructor and deconstructor. We can replace our Point record definition with the following, without loss of functionality

record Point (double X, double Y);

Like tuples, records exhibit structural equality by default. Records can subclass other records and can include the same constructs that classes can include. The compiler implements records as classes at runtime.

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %

About Author

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

3 thoughts on “Init-only setters in C#

  1. Wonderful goods from you, man. I’ve bear in mind your stuff prior to and you’re simply too fantastic. I actually like what you have bought here, really like what you’re saying and the way wherein you say it. You make it enjoyable and you still take care of to keep it wise. I can’t wait to read much more from you. This is really a wonderful web site.

  2. Just wish to say your article is as surprising The clearness in your post is just cool and i could assume youre an expert on this subject Fine with your permission allow me to grab your RSS feed to keep updated with forthcoming post Thanks a million and please keep up the enjoyable work

  3. of course like your website but you have to check the spelling on several of your posts A number of them are rife with spelling issues and I in finding it very troublesome to inform the reality on the other hand I will certainly come back again

Leave a Reply

Your email address will not be published. Required fields are marked *