jjk_charles
jjk_charles

Reputation: 1290

C# - Syntax for Object Initializers

So, I was modifying one of my codes and ended up writing something like this,

class TestClass
{
    static void Main(string[] args)
    {
        var lstObj = new List<List<string>>()
        {
            new List<string>() { "ABC","DEF", },
            new List<string>() {"GHI","JKL" },
        };
    }
}

Notice the extra comma (",") in following lines,

new List() { "ABC","DEF", }, //After "DEF"

new List() {"GHI","JKL" }, //After '}'

After realizing the typo, I decided to cancel the Build, correct it and restart the Build. But I was little too late, and to my surprise the Build already got completed successfully.

I am just wondering if this is proper syntax or if this has any special meaning to it.

Tried looking up for documentation supporting this but couldn't find any. Tried looking up the C# Language Specification and it is beyond me to comprehend anything related to this.

Upvotes: 1

Views: 156

Answers (3)

Martin
Martin

Reputation: 2096

C# allows extra commas at several places. Considering object initializers, the C# 5.0 Language Specification mentions in section 7.6.10.2:

object-initializer:
    {   member-initializer-list_opt   }
    {   member-initializer-list   ,   }

member-initializer-list:
    member-initializer
    member-initializer-list   ,   member-initializer

Note that the extra comma is explicitly allowed.

I think that this is a design decision to get rid of compiler errors that are of no use. Allowing that extra comma does not add any ambiguity to the language.

Upvotes: 5

Grace
Grace

Reputation: 651

C# ignores trailing commas in braced initializers. There exists at least one example of this construct in official Microsoft examples (see the student2 example), in addition to the section of spec Martin quotes. In your case:

new List<string>() { "ABC","DEF", },
new List<string>() {"GHI","JKL" },

is exactly equivalent to

new List<string>() { "ABC","DEF"},
new List<string>() {"GHI","JKL"}

As MK87 points out, it's a convenience thing. It lets you copy and paste list elements without having to worry about adding and removing trailing commas.

Upvotes: 4

Massimiliano Kraus
Massimiliano Kraus

Reputation: 3833

It can seem confusing if you haven't use it before, but it makes all the items syntactically equal, better-ordered and consequently easier to read. Also (more important), this syntax makes your code easier to change.

For example, suppose you have a 5-element list, you must cut the last element and put it in position 1.

With the last-without-comma sintax, you have to:

  1. cut the last element
  2. paste to position 1
  3. add a comma to this item
  4. delete the comma in the new last element

With the all-with-comma syntax, you must do only points 1 and 2.

Upvotes: 2

Related Questions