Is it safe to do this in C#?
field = Property = value;
Is it guaranteed that the setter and getter be called in succession and will field
only be assigned the result of the getter and not necessarily value
? Will the compiler optimize it away to just value
?
Using
private int tada;
public int TADA
{
get
{
Console.WriteLine("GETTER");
return tada;
}
set
{
Console.WriteLine("SETTER");
tada = value;
}
}
and
int s = TADA = 1;
I only get SETTER written to the output window, so it does not seem to call the getter.
From C# Language Fundamentals
You can even assign the same value to multiple variables, like this:
int a, b, c, d;
a = b = c = d = 5;
In this case, a, b, c, and d would all have the value 5. This works because the C# compiler performs the rightmost assignment first; that is, d = 5. That assignment itself returns a value, the value 5. The compiler then assigns that returned value to c. That second assignment also returns a value, and so on, until all the variables have been assigned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With