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
updated