Object initialisers and Collections
Starting with .NET 3, we've received some pretty cool new syntax in C#, things that made coding a bit more pleasant, and the code look somewhat more tidy. One of these additions was the object initialiser syntax!
Basically, what it allows you to do is initialise an object, and assign a bunch of properties to this object in a single statement, instead of 1 statement per each assignment. Apart from reducing the number of statements, and grouping all these assignments (which improves readability as well), this was also used in initialising anonymous class variables, and using simple single-statement lambdas, but that's not the point of this page :)
While this works great in most cases, there's one situation where I thought I didn't have a choice than to assign some values outside the initialiser, and this was readonly collections! Because the object initialiser is used to assign values to properties, I couldn't use it to create a new object with some values in a readonly collection property, because every time I tried - I got a exception.
new DataTable
{
Columns = new[] { new DataColumn("FirstCol") }
}
What I didn't know at the time was that this was easily fixed by using another well-known addition in .NET 3 - the array / collection initialiser!