Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hi, I copied the code from
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/init
But it seems init block didn't execute in object construction phase. I expect Field1, Field2, Prop1 all be 13.
Any suggestion? Thanks!
Complex c = new ();
Console.WriteLine($"Field1 : {c.Field1}");
Console.WriteLine($"Field2 : {c.Field2}");
Console.WriteLine($"Prop1 : {c.Prop1}");
Console.WriteLine($"Prop2 : {c.Prop2}");
/*
* Field1 : 0
* Field2 : 0
* Prop1 : 0
* Prop2 : 42
*/
class Complex {
public readonly int Field1;
public int Field2;
public int Prop1 {
get; init;
}
public int Prop2 {
get => 42;
init {
Field1 = 13;
Field2 = 13;
Prop1 = 13;
}
}
}
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
Complex c = new () {Prop2 = 0};
or in constructor:
Complex() {
Prop2 = 0;
}
property init must be called explicitly because otherwise we don't know init execution order of different properties.