Alperen Yaşar
Alperen Yaşar

Reputation: 1

Is there any way to set multiple variables in one operation c#

Pals, I'm new to in c# I just wonder, Is there any way to set multiple variables in one operation

My code is:

public class Program
{
    public static void Main()
    {

        int a = 5;
        int b = 5; 
        a += 1;
        b -= 1;

        Console.WriteLine(a);
        Console.WriteLine(b);
    }
}

However I want to write them on one line like that:

        int a = 5;
        int b = 5; 
        a += b -= 1;

        Console.WriteLine(a);
        Console.WriteLine(b); 

Upvotes: 0

Views: 113

Answers (1)

Sweeper
Sweeper

Reputation: 271040

You can use the tuple deconstruction syntax introduced in C# 7 to write

a += 1;
b -= 1;

in one line:

(a, b) = (a + 1, b - 1);

Note that unlike the original statements, this will evaluate a and b twice. This is fine if a and b are local variables, but not if a and b have side effects. I personally find the original 2 line version easier to read anyway.

a += b -= 1 does not mean the same thing. It means:

int temp = b - 1;
b = temp;
a += temp;

Upvotes: 2

Related Questions