Share via

property init problem

Zhu, Shenli 21 Reputation points
2022-08-01T02:46:31.31+00:00

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;   
        }  
    }  
}  
Developer technologies | C#
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.

0 comments No comments

1 answer

Sort by: Most helpful
  1. Zhu, Shenli 21 Reputation points
    2022-08-01T04:45:47.547+00:00
    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.

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.