C#: Assign same value to multiple variables in single 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.
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.