Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple assignment (field = Property = value)

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?

like image 428
Monstieur Avatar asked Jun 21 '13 09:06

Monstieur


1 Answers

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.

like image 155
Adriaan Stander Avatar answered Oct 24 '22 07:10

Adriaan Stander