Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What "Init only setters" provides and what is the difference to the readonly one in C# [duplicate]

Tags:

c#

c#-9.0

I can define a class like below:

public class MyClass
{
  public int Id { get; }
  public MyClass(int id) => Id = id;
}

And I have to define the Id from the constructor and it will be read-only.

But if I want to use Init only setters in the C# 9.0, what does it and how can I use it?

public class MyClass
{
  public int Id { get; init; }
}
like image 342
Sasa Avatar asked Jan 25 '23 10:01

Sasa


1 Answers

In a nutshell:

var obj = new MyClass
{
    Id = 42 // totally fine
};

obj.Id = 43; // not OK, we're not initializing

Trivial in this case and not much different to using a constructor parameter, but useful in some more complex scenarios where you don't want 200 constructor parameters, but you do want it to be outwardly immutable once constructed.

like image 100
Marc Gravell Avatar answered Jan 26 '23 23:01

Marc Gravell