Since it seems to be the prime subject of all duplicate related post about setting only once a property, I post my custom solution here.
To be brief, I took advantage of source generator to automatically generate back-end code of WriteOnce<T>
a-like. (mine is called SettableNTimesProperty<T>
but have kind of same purpose).
This end up being used like following.
Lets say you have this DTO class :
internal class DTO
{
int ID { get; init; }
string Name { get; init; }
public DTO(int id, string name = "Default_DTO_Name")
{
ID = id;
Name = name;
}
}
In order to make its properties settable only once instead of using init
, modify your code this way :
internal partial class DTO : IDTO
{
public DTO(int id, string name = "Default_DTO_Name")
{
((IDTO)this).ID = id;
((IDTO)this).Name = name;
}
}
and add this interface
using SetOnceGenerator;
public interface IDTO
{
[SetOnce]
int ID { get; set; }
[SetOnce]
string Name { get; set; }
}
If you want to allow multiple set
, up to n
times maximum, use [SetNTimes(n)]
attribute instead of [SetOnce]
You can check it here.