-
When using initializers I mean init or required the object must be created beforehand and the values are set afterwards, right, so initializer are always set after construction struct Data
{
public int Value {get; init;}
}
var v = new Data()
{
Value = 10;
} some value are calculated depending on the incoming values though. But there is no way to call the constructor afterwards, right struct Data
{
public int Value {get; init;}
public int Value2 {get; }
public Data()
{
// Value is still 0
Value2 = Value * 10;
}
}
var v = new Data()
{
Value = 10;
} I'm asking this because of course I could make
which might be a performance sensitive thing, so the question is if some method could be emitted that is still in the context of a constructor, meaning I could still modify readonly members? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Initializer blocks are currently compiled into a call to the constructor followed by separate assignments to each property: var v = new Data() {
Value = 10;
};
// compiles into
var $temp = new Data();
$temp.Value = 10;
var v = $temp; There are no methods automatically invoked at the end of an initializer in which you could inject this logic. Currently the best you could probably do in this specific case would be to have the accessor for the property set the other property to the appropriate value: struct Data {
private int _value;
public int Value {
get => _value;
init {
_value = value;
Value2 = value * 10;
}
}
public int Value2 { get; private set; }
} |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
https://github.com/dotnet/csharplang/blob/main/meetings/2020/LDM-2020-04-27.md#primary-constructor-bodies-and-validators
https://github.com/dotnet/csharplang/blob/main/meetings/2020/LDM-2020-05-04.md#final-initializers
https://github.com/dotnet/csharplang/blob/main/meetings/2020/LDM-2020-07-20.md#future-record-direction
https://github.com/dotnet/csharplang/blob/main/meetings/2021/LDM-2021-09-01.md#c-11-initialization-triage