Search code examples
c#.netcollectionsnullreferenceexceptionduck-typing

Why Collection Initialization Throws NullReferenceException


The following code throws a NullReferenceException:

internal class Foo
{
    public Collection<string> Items { get; set; } // or List<string>
}

class Program
{
    static void Main(string[] args)
    {
        new Foo()
            {
                Items = { "foo" } // throws NullReferenceException
            };
    }
}
  1. Why don't collection initiliazers work in this case, although Collection<string> implements the Add() method, and why is NullReferenceException is thrown?
  2. Is it possible to get the collection initializer working, or is Items = new Collection<string>() { "foo" } the only correct way to initialize it?

Solution

  • You never instantiated Items. Try this.

    new Foo()
        {
            Items = new Collection<string> { "foo" }
        };
    

    To answer your second question: You need to add a constructor and initialize Items over there.

    internal class Foo
    {    
        internal Foo()
        {
            Items  = new Collection<string>();
        }
        public Collection<string> Items { get; private set; }
    }
    

    Why your code throws NullReferenceException?