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!
This question is related to
c#
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
Something like this.
num1 = num2 = 5
Something a little shorter in syntax but taking what the others have already stated.
int num1, num2 = num1 = 1;
It is simple.
int num1,num2;
num1 = num2 = 5;
num1 = num2 = 5
int num1=5,num2=5
Declaring and assigning variables in the same statement.
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.
Your example would be:
int num1 = 1;
int num2 = 1;
num1 = num2 = 5;
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.
Source: Stackoverflow.com