Coder Perfect

In a single statement in C#, assign the same value to many variables.


Is there a way in C# to assign one value to numerous variables at once in a single statement (just out of curiosity because I came across multiple same-value assignments to multiple variables today)?

Something similar to this (pseudocode):

int num1 = 1;
int num2 = 1;

num1 & num2 = 5;

Although I doubt it, I felt it was worth asking in case something similar is possible!

Asked by Alex

Solution #1

It is as straightforward as this:

num1 = num2 = 5;

When utilizing an object property instead of a variable, it’s worth noting that the intermediate value’s get accessor isn’t invoked. For all properties accessible in the assignation sequence, only the set accessor is used.

Consider a class that writes to the console whenever the get and set accessors are called.

static void Main(string[] args)
    var accessorSource = new AccessorTest(5);
    var accessor1 = new AccessorTest();
    var accessor2 = new AccessorTest();

    accessor1.Value = accessor2.Value = accessorSource.Value;


public class AccessorTest
    public AccessorTest(int value = default(int))
        _Value = value;

    private int _Value;

    public int Value
            Console.WriteLine("AccessorTest.Value.get {0}", _Value);
            return _Value;
            Console.WriteLine("AccessorTest.Value.set {0}", value);
            _Value = value;

This will output

AccessorTest.Value.get 5
AccessorTest.Value.set 5
AccessorTest.Value.set 5

That is, the compiler will assign the value to all properties without re-reading it each time it is assigned.

Answered by Pierre-Alain Vigeant

Solution #2

This is what you’re looking for:

int num1, num2;
num1 = num2 = 5;

The assignment ‘num2 = 5’ will return the assigned value.

This allows you to do crazy things like num1 = (num2 = 5) +3; which assigns 8 to num1, but I wouldn’t encourage it because it’s hard to read.

Answered by aaronb

Solution #3

int num1=5,num2=5

Using the same statement to declare and assign variables.

Answered by Zain Ali

Solution #4

Something a little more succinct in syntax, but still incorporating what the others have said.

int num1, num2 = num1 = 1;

Answered by abuss

Solution #5

In C#, this is now possible:

var (a, b, c) = (1, 2, 3);

You’ve basically declared three variables by doing the above. a = 1, b = 2, and c = 3 are the values of a, b, and c. Everything is written in a single line.

Answered by Rikki

Post is based on