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
};
}
}
Collection<string>
implements the Add()
method, and why is NullReferenceException is thrown?Items = new Collection<string>() { "foo" }
the only correct way to initialize it?Thanks guys. As summary collection initializer doesn't create instance of collection itself, but just uses Add() to add items to existant instance, and throws NullReferenceException if instance doesn't exist
1.
internal class Foo
{
internal Foo()
{
Items = new Collection<string>();
}
public Collection<string> Items { get; private set; }
}
var foo = new Foo()
{
Items = { "foo" } // foo.Items contains 1 element "foo"
};
2.
internal class Foo
{
internal Foo()
{
Items = new Collection<string>();
Items.Add("foo1");
}
public Collection<string> Items { get; private set; }
}
var foo = new Foo()
{
Items = { "foo2" } // foo.Items contains 2 elements: "foo1", "foo2"
};
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With