This morning I took out a comma and this afternoon I put it back in again.
Oscar Wilde

Drawing on my fine command of the English language, I said nothing.
Robert Benchley, As quoted in: With Truth as Our Sword (2005) by C E Sylvester, p. 205

He who establishes his argument by noise and command shows that his reason is weak.
Michel de Montaigne

In C# Version 3, I have found a coding style which I would expect to give a compile error but does not.  By using this unexpected “flaw” or “feature”, my code maintenance is easier.

I sometimes use predefined lists of objects.  The features of C#, version 3, make this very easy to do and highly readable.  Over time, I quite often must add more entries in the list.  Each object add to the list is separated by a comma.  I would expect the last entry to be added to NOT have a comma.  By chance, I have found the last entry can have a comma and the program will compile.

When I do not have to worry about the last comma, copy and paste are very easy when new entries are required.

Start with a simple data class called Customer.

public class Customer
{
  public string Name { get; private set; }
  public string Email { get; set; }
  public string PhoneCell { get; set; }
  public string PhoneWork { get; set; }
  public string PhoneHome { get; set; }

  public Customer(string name)
  {
    Name = name;
  }
}

This is the code I expected that is required for error free compile.

List<Customer> customerList = new List<Customer>()
{
  new Customer("John"){PhoneCell = "555 345-6789", PhoneWork = "555 344-9892"},
  new Customer("Mary"){PhoneCell = "555 345-9911", Email = "Phoney Email"},
  new Customer("Sue"){PhoneHome = "555 872-2381"}
};

But notice, this code will also compile. The trailing comma after new Customer Sue is allowed by the compiler. I have highlighted this row.

List<Customer> customerListWithExtraComma = new List<Customer>()
{
  new Customer("John"){PhoneCell = "555 345-6789", PhoneWork = "555 344-9892"},
  new Customer("Mary"){PhoneCell = "555 345-9911", Email = "Phoney Email"},
  new Customer("Sue"){PhoneHome = "555 872-2381"},
};

Tags:

Leave a Reply


*