207

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

Something along these lines (pseudocode):

int num1 = 1;
int num2 = 1;

num1 & num2 = 5;

Probably not but I thought it was worth asking in case something similar is actually possible!

Dharman
  • 30,962
  • 25
  • 85
  • 135
Alex
  • 75,813
  • 86
  • 255
  • 348

10 Answers10

334

It's as simple as:

num1 = num2 = 5;

When using an object property instead of variable, it is interesting to know that the get accessor of the intermediate value is not called. Only the set accessor is invoked for all property accessed in the assignation sequence.

Take for example a class that write to the console everytime the get and set accessor are invoked.

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

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

    Console.ReadLine();
}

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

    private int _Value;

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

This will output

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

Meaning that the compiler will assign the value to all properties and it will not re-read the value every time it is assigned.

Pierre-Alain Vigeant
  • 22,635
  • 8
  • 65
  • 101
  • 48
    Its not weird actually. The logic is as follows: The assignment operation itself returns a value, which is the value that has been assigned. The sequence of execution is: ``num1 = (num2 = 5)`` and the first assignment which is executed (``num2 = 5``) returns the value 5 to the outside world - which is in turn assigned to num1. This works ad infinitum (``num0 = num1 = num2 = 5``). – Jpsy Jan 21 '12 at 19:36
  • If you want to test it, try `Console.WriteLine(num = 5);`. (Disclaimer: I haven't yet) – Arlen Beiler May 09 '13 at 19:36
  • 3
    Question: Is this considered bad practice `num1 = num2 = 5`? Does it turn code unreadable if more variables are involved? Sorry to hijack, I didn't want to create a new post just for it. – johnildergleidisson Dec 03 '13 at 15:28
  • There is no correct answer. I use it only scarcely in my program and I could have avoided it. – Pierre-Alain Vigeant Dec 03 '13 at 18:21
  • Down to coding style I assume then. Thanks for the reply. – johnildergleidisson Dec 03 '13 at 19:10
  • another (separate) example could be to have a third property and do a=b=c and see how many times the "get" accessor of the c property was called – George Birbilis Aug 21 '15 at 16:23
  • I had the same doubt just like John wondering about bad practices in this multiple assignation subject. – Josue Rocha Jan 30 '20 at 18:24
  • And also I'm wondering if there's any performance in this or is it just saving you a line of code?... – Josue Rocha Jan 30 '20 at 18:25
  • @JosueRocha You can easily validate by compiling and using a decompiler tool and see what is the actual result. – Pierre-Alain Vigeant Feb 01 '20 at 02:59
  • I am also unsure about it. I like the clarity of `Head.Position = Tail.Position = position`. This means, they do not get the same value by accident, but you really want it to be exactly the same value. This might get lost, if you first assign three values do three properties of Head and afterwards the exact same values to Tail. But I am not sure, if I like it in the long run. – Sebastian Werk Jul 15 '21 at 20:30
  • In response to "Is it considered bad practice?", generally no. I see it quite often in production level code, and most of the time it really helps tidy things up. Just be aware of scenarios where it can make it more difficult to read. Compiled code wise, it's exactly the same as doing it one by one, so it's really up to readability. – Nemo May 01 '22 at 02:49
  • var a = b = c = SomeObject; any change later made to a or b or c will affect all of them. – Rajeev Menon Dec 12 '22 at 16:10
  • @RajeevMenon That's not an effect of the chained/multiple assignment. Had they been written as three separate assignments, changing the assigned object would still affect a, b, and c. But a change such as c = AnotherObject would not affect a or b — again true regardless of the way the variables were initially assigned. – Rich Armstrong Mar 14 '23 at 14:47
68

This will do want you want:

int num1, num2;
num1 = num2 = 5;

'num2 = 5' assignment will return the assigned value.

This allows you to do crazy things like num1 = (num2 = 5) +3; which will assign 8 to num1, although I would not recommended doing it as not be very readable.

aaronb
  • 2,149
  • 15
  • 8
38
int num1 = 5, num2 = 5;

Declaring and assigning variables in the same statement.

dana
  • 17,267
  • 6
  • 64
  • 88
Zain Ali
  • 15,535
  • 14
  • 95
  • 108
32

Something a little shorter in syntax but taking what the others have already stated.

int num1, num2 = num1 = 1;
abuss
  • 349
  • 3
  • 3
29

This is now a thing in C#:

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

By doing the above, you have basically declared three variables. a = 1, b = 2 and c = 3. All in a single line.

Rikki
  • 3,338
  • 1
  • 22
  • 34
  • 3
    Woah, didn't know this. Can you provide a link to documentation? – Dave Oct 12 '20 at 19:58
  • 4
    https://learn.microsoft.com/en-us/dotnet/csharp/deconstruct "Starting with C# 7.0, you can retrieve multiple elements from a tuple or retrieve multiple field, property, and computed values from an object in a single deconstruct operation. When you deconstruct a tuple, you assign its elements to individual variables. When you deconstruct an object, you assign selected values to individual variables." – Rikki Oct 13 '20 at 20:17
  • 2
    A colleague of mine showed some code that used this syntax in a demo this morning. I've been writing C# since 2003, but this was new to me. Thanks for your comment, and the link to the documentation. – Mike Waldron Oct 08 '21 at 21:05
  • 1
    Don't forget that tuple members can have different types, so this works, too:   var (d, i, s) = (6.28, 42, "Hello"); – Rich Armstrong Mar 14 '23 at 14:24
11

Try this:

num1 = num2 = 5;

Note that this won't work in VB.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 1
    Do you know if there is some alternate syntax for VB developers, or is multiple assignment simply not available in VB? – ckittel Jun 25 '11 at 20:50
  • 3
    @cki: AFAIK, it's not supported. – SLaks Jun 26 '11 at 02:33
  • @ckittel In VB `=` is used both for assignment and equality, so `num1 = num2 = 5` would mean "assign the boolean result of whether or not five is equal to `num2` to the variable `num1`". Because the `=` operator has these two meanings, there is no way to represent this syntax. The best you could do is create a function that took in a number of parameters `byref` as well as a value and assigned all of the parameters to that value. – Servy Feb 14 '13 at 19:35
7

num1 = num2 = 5

Daniel
  • 2,744
  • 1
  • 31
  • 41
6
int num1, num2, num3;

num1 = num2 = num3 = 5;

Console.WriteLine(num1 + "=" + num2 + "=" + num3);    // 5=5=5
LukeH
  • 263,068
  • 57
  • 365
  • 409
6

Your example would be:

int num1 = 1;
int num2 = 1;

num1 = num2 = 5;
Druid
  • 6,423
  • 4
  • 41
  • 56
5

Something like this.

num1 = num2 = 5
Rohan West
  • 9,262
  • 3
  • 37
  • 64