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


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

Updated on: 20-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements