I have a strange issue with the object initializer syntax.
Here are my sample classes:
public class Foo
{
public Bah BahProp { get; set; }
}
public class Bah
{
public int Id { get; set; }
}
Consider following three ways to initialize an object:
The old, verbose but explicit way, working correctly:
var foo1 = new Foo();
foo1.BahProp = new Bah();
foo1.BahProp.Id = 1;
// correctly initialized
The second way i'm always using, using object initializer syntax:
var foo2 = new Foo
{
BahProp = new Bah { Id = 1 }
}; // correctly initialized
A third way resharper has suggested my collegue with a different resharper version(is it a bug?):
var foo3 = new Foo
{
BahProp = { Id = 1 }
}; // NullReferenceException
What is the last approach doing differently?
My resharper version is 2016.1.1, my colleague was on 10.02. My resharper suggested the second way. But what does the third way do and when is it useful?
Update: So it seems that it was a bad resharper sugestion to use the last way, that's why they have changed it meanwhile to use the second way.
You can avoid the NullReferenceException
if you want to use the third way by initializing all properties/fields that are reference types inline or in the constructor.
I will definitely not use this strange property assignment syntax.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…