The object initializer does not seem to match the purpose of contructor + property. How so?

Consider the code below:

class Data
{
    public string Name;
    public string NameWithSufix;
}

class Behaviour
{
    private Data data;
    public string Name { get { return data.Name; } private set { } }

    public Behaviour()
    {
        data = new Data()
        {
            Name = "My Name",
            NameWithSufix = Name + " Sufix",
        };
        //data = new Data();
        //data.Name = "My Name";
        //data.NameWithSufix = Name + " Sufix";
    }
}

class Program
{
    static void Main(string[] args)
    {
        Behaviour behaviour = new Behaviour();
    }
}

If you run this program, it will fail with a NullReferenceException in the Name property. This and this , and Visual Studio will try to convince me of the initialization of the object and the constructors of the objects, followed by the assignment of properties - this but it does not look like. If I change the constructor body with commented code, it works. It seems that initiliazer does not actually start the constructor before trying to assign properties. Why?

+4
source share
2 answers

Name NameWithSufix = Name data.Name, data . :

Data d = new Data();
d.Name = "My Name";
d.NameWithSufix = this.data.Name /*Name*/ + " Sufix"; // <-- see the problem here

this.data = d;

, this.data , .

#, PetSerAl.

+4

Behavior. , Data ,

NameWithSufix = Name + " Sufix",

get { return data.Name; }, Data null .


Update:

- , Data , Data.

, - , .

+3

Source: https://habr.com/ru/post/1689498/


All Articles