compiler accepts almost-object-initializer that throws NullReferenceException [duplicate]
-
09-01-2021 - |
Question
Possible Duplicate:
Initializer syntax
Short code sample to demonstrate (VS2010 SP1, 64-bit Win7):
class A
{
public string Name { get; set; }
}
class B
{
public A a { get; set; }
}
// OK
A a = new A { Name = "foo" };
// Using collection initialiser syntax fails as expected:
// "Can only use array initializer expressions to assign
// to array types. Try using a new expression instead."
A a = { Name = "foo" };
// OK
B b = new B { a = new A { Name = "foo" } };
// Compiles, but throws NullReferenceException when run
B b = new B { a = { Name = "foo" } };
I was surprised to see that last line compile and thought I'd found a nifty (though inconsistent) shortcut before seeing it blow up at runtime. Does that last usage have any utility?
Solution
The last line is translated to:
B tmp = new B();
tmp.a.Name = "foo";
B b = tmp;
And yes, it very definitely has utility - when the newly created object has a read-only property returning a mutable type. The most common use of something similar is probably for collections though:
Person person = new Person {
Friends = {
new Person("Dave"),
new Person("Bob"),
}
}
This will fetch the list of friends from Person
and add two new people to it.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow