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 NullReferenceException at Name property. This and this answer and Visual Studio try to persuade me object initializer and object constructors followed by property assignment are the same but it doesn't seem so. If I swap the body of constructor with commented code, it works. It seem like initiliazer doesn't actually run the constructor before it tries to assign properties. Why?