Wednesday, June 15, 2016

A trailing comma in a collection doesn't stop the compiler in C#.

The following test passes. The fourth comma is harmless all and all. Just as you can get away with a semicolon on a line all by itself you may have a trailing comma without consequence.

using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestProject
{
   [TestClass]
   public class UnitTest
   {
      [TestMethod]
      public void Go()
      {
         List<string> whatever = new List<string>() { "foo", "bar", "baz", "qux", };
         Assert.AreEqual(whatever[0], "foo");
         Assert.AreEqual(whatever[1], "bar");
         Assert.AreEqual(whatever[2], "baz");
         Assert.AreEqual(whatever[3], "qux");
      }
   }
}

No comments:

Post a Comment