Order of operations using Object Initializer Syntax

前端 未结 1 954
情深已故
情深已故 2020-11-28 16:01

Does the order in which I set properties using the object initializer syntax get executed in the exact same order?

For instance if I do this:

var s =         


        
相关标签:
1条回答
  • 2020-11-28 16:05

    Yes.

    Apologies for getting interrupted (I have to actually do some work every so often). The spec doesn't explicitly say it, but it makes it pretty clear IMO in section 7.6.10.2:


    An object initializer consists of a sequence of member initializers, enclosed by { and } tokens and separated by commas.

    (Note the word "sequence" here, rather than "set". I personally think that's significant, as a sequence is ordered.)

    The following class represents a point with two coordinates:

    public class Point
    {
        int x, y;
        public int X { get { return x; } set { x = value; } }
        public int Y { get { return y; } set { y = value; } }
    }
    

    An instance of Point can be created and initialized as follows:

    Point a = new Point { X = 0, Y = 1 };
    

    which has the same effect as

    Point __a = new Point();
    __a.X = 0;
    __a.Y = 1; 
    Point a = __a;
    

    where __a is an otherwise invisible and inaccessible temporary variable.


    EDIT: I've had a response from Mads Torgersen, who has basically said that anything which can be done now will preserve the order. There may be some oddities in future where the order is not preserved in weird cases where you're doing something other than setting a property/field, but that will depend on where the language goes.

    It's worth pointing out that there are actually lots of steps going on here - there's the order of execution of the evaluation of the arguments (i.e. the RHS bits) and the order of execution of the assignments. For example, if you have:

    new Foo
    {
        A = X,
        B = Y
    }
    

    all the following orders are possible while still maintaining the order of the actual property execution (A and B):

    • Evaluate X, assign to A, evaluate Y, assign to B
    • Evaluate X, evaluate Y, assign to A, assign to B
    • Evaluate Y, evaluate X, assign to A, assign to B

    I believe the first option is the one actually taken, but this was just to demonstrate that there's more to it than meets the eye.

    I would also be very wary of actually writing code which depends on this...

    0 讨论(0)
提交回复
热议问题