How to assign same value to multiple variables in single statement in C#?

CsharpProgrammingServer Side Programming

To assign same value to multiple variables in a single line, use the = operator −

val1 = val2 = 20;

The above statement assigns 20 to the variables val1 and val2 as shown in the following code −

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demo {
   class MyApplication {
      static void Main(string[] args) {
         int val1, val2;
         val1 = val2 = 20;
         Console.WriteLine("Value1 = "+val1);
         Console.WriteLine("Value2 = "+val2);
      }
   }
}

Output

Value1 = 20
Value2 = 20
raja
Published on 08-Aug-2018 12:23:46
Advertisements