The following code compiles, but fails with a NullReferenceException:
class Test
{
public Dictionary<string, string> Dictionary { get; set; }
}
static void Main(string[] args)
{
var x = new Test
{
Dictionary = // fails
{
{ "key", "value" }, { "key2", "value2" }
}
};
}
If you replace the line marked ‘fails’ with the following, it works (as expected):
Dictionary = new Dictionary<string, string>
Is there any purpose to the failing syntax–can it be used successfully in some other case? Or is this an oversight in the compiler?
No, it’s not a mistake… it’s a flaw in your understanding of initialization syntax 🙂
The idea of the
is for cases where the caller has read access to a collection property, but not write access. In other words, situations like this:
Basically it ends up being calls to Add, but without creating a new collection first. So this code:
is equivalent to:
A good example of where this is useful is with the
Controlscollection for a UI. You can do this:but you couldn’t actually set the
Controlsproperty, because it’s read-only.