C# Object Initializers. More than meets the eye

Up till today I liked C# object initializers because the looked nicer and when using parameter objects they even turn into something like named parameters.

But just a couple of minutes ago I was changing some test data creation code that didn't use object initializers but plain property assignments.

As I use ReSharper I alt-returned the assignments into an initializer. What struck me was that not all property assignments where put into the initializer.

Why? Because the same property had two assignments (of course with different values). I only noticed that when I was trying to incorporate the assignment into the initializer and the red squiglies from ReSharper. The C# compiler issues an error when you try to compile this type of code:
error CS1912: Duplicate initialization of member 'X'
So object initializers not only look better, they prevent you from making such a dumb mistake.

No comments:


whos online

Ralf"s shared items