C#: Assign same value to multiple variables in single statement



4 Answers

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.

Question

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!




Try this:

num1 = num2 = 5;

Note that this won't work in VB.




int num1, num2, num3;

num1 = num2 = num3 = 5;

Console.WriteLine(num1 + "=" + num2 + "=" + num3);    // 5=5=5



It is simple.

int num1,num2;
num1 = num2 = 5;



Your example would be:

int num1 = 1;
int num2 = 1;

num1 = num2 = 5;



Related



Tags

c# c#