Why does it compile?

            var cv = (new CustomValidator()
            {
                 ErrorMessage="Formato de telefone inválido",
                 ControlToValidate = "txtTelefoneIni", //<-- see the extra comma
            });
+5
source share
8 answers

Because it is legal syntax.

Indeed it is.

When you create an object using the object initializer syntax, you can leave a trailing comma after the last element, even if you end there with an initialization block.

Probably the reason is that it makes it easier to return and edit later, because it forgets to add a comma after the previous-last element is a compilation problem # 1 with object initializers.

+12
source

This is intentional. Also working on enumeration members. (so it’s easier to add more material)

+2
source

?

Python.

+2

, #.

string [] meh = { "a", "b", "c",};

+2

#: .

+2

. , ( "" ) , .

+1

#

var c = new List<int>() { 1, 2, 3 ,};
+1

FWIW, C.

My favorite reason for using this syntax (especially when defining enumerations) is that when you add an item to the list, the original control sees changes in only one line (new). It does not put the previous one as modified (due to the added comma). It is much more convenient to read.

My 2 cents.

+1
source

All Articles