Why do we use comma operator in C#?

CsharpProgrammingServer Side Programming

Comma operator in C# can be used as a separator in method argument list. You can also use it is an operator in a for statement.

The following is an example showing using a comma operator in a for statement for initialization −

for (int i = begin, j = 1; i <= end; i++, j++)

Use it in Console.WriteLine for displaying the values as well −

Console.Write("{0} : {1} ", i, (char)i);

Here is the complete code −

Example

 Live Demo

using System;
class Demo {
   const int begin = 45;
   const int end = 60;
   const int line = 1;

   static public void Main() {
      for (int i = begin, j = 1; i <= end; i++, j++) {
         Console.Write("{0} : {1} ", i, (char)i);
         if (0 == (j % line)) {
            Console.WriteLine("");
         }
      }
   }
}

Output

45 : -
46 : .
47 : /
48 : 0
49 : 1
50 : 2
51 : 3
52 : 4
53 : 5
54 : 6
55 : 7
56 : 8
57 : 9
58 : :
59 : ;
60 : <
raja
Published on 07-Aug-2018 12:44:07
Advertisements