1

I'm reviewing this code (written in C#):

string root = match.Groups[1].Value,
                secon = match.Groups[2].Success ? match.Groups[2].Value.Substring(1) : string.Empty,
                third = match.Groups[3].Success ? match.Groups[3].Value.Substring(1) : string.Empty;

Can someone explain the purpose of the commas?

Alexey
  • 3,607
  • 8
  • 34
  • 54
  • 3
    Ugh, this is a good example of how *not* to use that syntax. This question only exists because the syntax is so hard to read and understand. With all the whitespace, the code actually would've been *shorter* had it been written in the usual way. – Tim S. Apr 29 '13 at 17:07
  • @TimS. is right; this is a good example of how to abuse the feature. Still, it could be worse. In early versions of Visual Basic, `Dim Curly, Larry, Moe as Stooge` meant of course that `Curly` and `Larry` were `Variant` and Moe was `Stooge`. – Eric Lippert Apr 29 '13 at 18:25

3 Answers3

5

It declares 3 variables of the type string named root, secon and third respectively. Like this:

int a, b, c;
nmat
  • 7,430
  • 6
  • 30
  • 43
3

It's a syntactic shortcut. Your example above is syntactic sugar for and is exactly the same as:

string root  = match.Groups[1].Value   ;
string secon = match.Groups[2].Success ? match.Groups[2].Value.Substring(1) : string.Empty ;
string third = match.Groups[3].Success ? match.Groups[3].Value.Substring(1) : string.Empty ;

So it saves you a little typing.

That is all.

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
  • One can also use the `var` keyword. In that case it is never allowed to put multiple declarations together with commas. – Jeppe Stig Nielsen Apr 29 '13 at 17:42
  • @JeppeStigNielsen: There is *one* situation in which it is legal to put multiple declarations in one statement with `var`. Can you guess what it is? – Eric Lippert Apr 29 '13 at 18:24
  • @EricLippert I am curious, as per your answer [here](http://stackoverflow.com/a/4950600/1029916) and my understanding of the language, it isn't allowed at all. – NominSim Apr 29 '13 at 18:31
  • @EricLippert Do you mean if I have declared a class (or struct, interface, enum, delegate) with the funny name `var`, as in `class var { }`? – Jeppe Stig Nielsen Apr 29 '13 at 18:36
  • @JeppeStigNielsen: You got it! The compiler checks to see if there is already a type in scope named `var` and only if there is not does it go into implicitly typed local mode. – Eric Lippert Apr 29 '13 at 21:03
0

They are used as a shortcut to create variables, and, in your example, all of which are of type string.

Ric
  • 12,855
  • 3
  • 30
  • 36