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
int num1, num2, num3;
num1 = num2 = num3 = 5;
Console.WriteLine(num1 + "=" + num2 + "=" + num3); // 5=5=5
Something a little shorter in syntax but taking what the others have already stated.
int num1, num2 = num1 = 1;
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.
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.
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.