Sunday, 11 July 2010

C# Object Initialisers and trailing commas

C# 3.0 (.NET 3.5) introduced some really handy new features and hidden gems—and I'm still coming across the latter today.

If you've been developing with C# 3.0 for a while, you'll know about object and collection initialisers: they allow you to initialise the members of an object or a collection at instantiation-time, rather than having to declare a variable and then assign values to the members of that variable. It's a convenience thing and makes life easier in a LINQ context (although the debugging experience in VS2008 sucks).

When looking back through a piece of code I written previously, I noticed I'd inadvertently left a trailing comma after the final assignment in the list. I thought this was unusual because the code compiled and the C# is normally anything but lazy when it comes to most language constructs.

StaffMember staffMember = new StaffMember()
{
    FirstName = "Michael",
    Surname = "Hanes",
};

Sure enough, the ECMA C# Language Specification actually notes the following in the section about Array Initializers: "[…] C# allows a trailing comma at the end of an array-initializer. This syntax provides flexibility in adding or deleting members from such a list […]" (page 363, section 19.7). Interestingly, object and collection initialisers simply inherit this behaviour and the ability to initialise both arrays and enums in this way is not C# 3.0-specific (the specification document actually cites the C language).

In my opinion this is a rational design decision that increases the useability of the C# language by developers. By contrast, I'm forever having to shift SQL select statement commas around when commenting out individual lines and it's a major inconvenience. Development is normally a very fluid, experimental time in the lifecycle of a code artefact and anything that simplifies that exercise and increases maintainability is a good thing.

1 comment:

  1. Hey Michael. I totally agree. I like the flexibility the trailing comma gives us. For SQL, I got into the habit of putting every column name in a statement on a newline preceded by a comment. Something like (I indent columns to help readability - but it doesn't really show in this comment):

    SELECT ColumnA
    , ColumnB
    , ColumnC
    , ColumnD
    ...

    This makes it a bit easier to comment out a column, but does make statements span more lines. I'm usually happy with this trade-off.

    ReplyDelete

Spam comments will be deleted

Note: only a member of this blog may post a comment.