Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to assign same value to multiple variables in single statement in C#?
In C#, you can assign the same value to multiple variables in a single statement using the assignment operator. This technique is called chained assignment and works because the assignment operator returns the assigned value.
Syntax
Following is the syntax for assigning the same value to multiple variables −
variable1 = variable2 = variable3 = value;
The assignment is evaluated from right to left, so value is first assigned to variable3, then that result is assigned to variable2, and finally to variable1.
How It Works
The assignment operator (=) in C# returns the value being assigned. This allows you to chain multiple assignments together in a single statement. The evaluation happens from right to left, making it possible to assign the same value to multiple variables efficiently.
Using Chained Assignment with Integers
Example
using System;
class Program {
static void Main(string[] args) {
int val1, val2, val3;
val1 = val2 = val3 = 20;
Console.WriteLine("Value1 = " + val1);
Console.WriteLine("Value2 = " + val2);
Console.WriteLine("Value3 = " + val3);
}
}
The output of the above code is −
Value1 = 20 Value2 = 20 Value3 = 20
Using Chained Assignment with Different Data Types
Example
using System;
class Program {
static void Main(string[] args) {
string name1, name2, name3;
name1 = name2 = name3 = "John";
bool flag1, flag2;
flag1 = flag2 = true;
double price1, price2, price3;
price1 = price2 = price3 = 99.99;
Console.WriteLine("Names: " + name1 + ", " + name2 + ", " + name3);
Console.WriteLine("Flags: " + flag1 + ", " + flag2);
Console.WriteLine("Prices: " + price1 + ", " + price2 + ", " + price3);
}
}
The output of the above code is −
Names: John, John, John Flags: True, True Prices: 99.99, 99.99, 99.99
Key Rules
-
All variables must be of the same data type or compatible types.
-
Variables must be declared before using chained assignment.
-
The assignment operator returns the assigned value, enabling the chaining.
-
Evaluation happens from right to left in the assignment chain.
Conclusion
Chained assignment in C# allows you to assign the same value to multiple variables in a single statement using the = operator. This technique works because the assignment operator returns the assigned value, and the evaluation occurs from right to left, making your code more concise and efficient.
