C Sharp

Using the Comma Operator

A comma can serve not only as a separator in method argument lists, but also as an operator in a for statement. In both the initialization and step portions of a for statement, the comma operator can be used to delimit multiple statements that are processed sequentially. In the following example, I've taken the nested loop example from the previous section and converted it to a single for loop by using the comma operator: -

using System;
class CommaOpApp
{
    const int StartChar = 33;
    const int EndChar = 125;
    const int CharactersPerLine = 3;
    static public void Main()
    {
        for (int i = StartChar, j = 1; i <= EndChar; i++, j++)
        {
            Console.Write("{0}={1} ", i, (char)i);
            if (0 == (j % CharactersPerLine))
            {
                // New line if j is divisible by 3.
                Console.WriteLine("");
            }
        }
    }
}

Using the comma operator in the for statement can be powerful, but it can also lead to ugly and difficult-to-maintain code. Even with the addition of constants, the following code is an example of using the comma operator in a technically correct, but inappropriate, manner: -

using System;
class CommaOp2App
{
    const int StartChar = 33;
    const int EndChar = 125;
    const int CharsPerLine = 3;
    const int NewLine = 13;
    const int Space = 32;
    static public void Main()
    {
        for (int i = StartChar, extra = Space;
            i <= EndChar;
            i++, extra = ((0 == (i - (StartChar-1)) % CharsPerLine)
            ? NewLine : Space))
        {
            Console.Write("{0}={1} {2}", i, (char)i, (char)extra);
        }
    }
}

by BrainBellupdated
Advertisement: