Thursday, May 17, 2012

C# under the covers II

An initialisation problem I hit recently, a null pointer exception when initialising an object via an initialiser statement. This program is a simplified example --

which throws when initializing b.

Putting them together like this, it's obvious what I missed out in the second initializer : I'm not creating a new object to assign. But it's not obvious what the second case is actually doing, even though it compiles -- which in itself initially surprised me. So let's look at the IL and find out what that initialisation is actually doing...

which actually resolves to something like

So if we add a constructor and a sensible ToString to the type being initialised, thus

we see that the initialisation of a replaces the constructed values; whereas b adds to them.

Not sure how useful this is as the dictionary literal form only works in initializers like this, but it's another bit of living and learning.

Post a Comment