What do braces after C# new statement do?

前端 未结 7 1773
孤城傲影
孤城傲影 2020-12-13 08:29

Given the code below, what is the difference between the way position0 is initialized and the way position1 is initialized? Are they equivalent?

相关标签:
7条回答
  • 2020-12-13 08:59

    They are not quite equivalent - at least not in the general case. The code using an object initializer is closer to this:

    Position tmp = new Position();
    tmp.x = 3;
    tmp.y = 4;
    Position position1 = tmp;
    

    In other words, the assignment to the variable only occurs after the properties have been set. Now in the case where you're declaring a new local variable, that doesn't actually matter, and the compiler may well optimize to your first form. But logically, it does matter. Consider:

    Position p1 = new Position { x = 10, y = 20 };
    
    p1 = new Position { x = p1.y, y = p1.x };
    

    If that did the assignment to p1 first, you'd end up with 0 for both p1.x and p1.y. Whereas that's actually equivalent to:

    Position tmp = new Position();
    tmp.x = 10;
    tmp.y = 20;
    Position p1 = tmp;
    
    tmp = new Position();
    tmp.x = p1.y; // 20
    tmp.y = p1.x; // 10
    p1 = tmp;
    

    EDIT: I've just realised that you're using a struct rather than a class. That may make some subtle differences... but you almost certainly shouldn't be using a mutable struct to start with :)

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