NullReferenceException with object initializer suggested by resharper

后端 未结 1 853
醉话见心
醉话见心 2020-12-19 21:23

I have a strange issue with the object initializer syntax.

Here are my sample classes:

public class Foo
{
    public Bah BahProp { get; set; }
}

pub         


        
相关标签:
1条回答
  • 2020-12-19 21:33
    new Foo { BahProp = { Id = 1 } }
    

    compiles to:

    new Foo().BahProp.Id = 1;
    

    or, little more verbose:

    var foo3 = new Foo();
    foo3.BahProp.Id = 1;
    

    So BahProp is null. You're not constructing it.
    (This is perhaps the most confusing syntax in all of C#)
    Option 2 works because you're calling the constructor of Bah.

    Option 3 would also work if you initialize BahProp inside the constructor of Foo. It will have been constructed by the time BahProp = { Id = 1 } is called.

    The same is seen with collection initializers:

    public class Foo {
        public List<int> Numbers { get; set; }
    }
    
    var foo = new Foo { Numbers = { 1, 2, 3 } };
    

    This does not initialize the List. It only calls Add on it.

    You really must see new MyObject() { X = 1, Y = 2 } as two distinct parts:
    new MyObject() constructs a new object and
    { X = 1, Y = 2 } sets the values of its properties (and that's all it does).
    Object and collection initializers can be nested. The top-level initializer must follow a constructor, but a nested initializer does not.

    0 讨论(0)
提交回复
热议问题