What do braces after C# new statement do?

前端 未结 7 1772
孤城傲影
孤城傲影 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:44

    These are fully equivalent. The compiler actually just transforms the first version into the second one.

    The only difference between the two is that with the first, you can do nice thins, like pass the initialized version to a method:

    DoSomethingWithPoint(new Position() { x=3, y=4 });
    

    This is a lot more lines of code than the second initialization example.

    0 讨论(0)
  • 2020-12-13 08:46

    Your two code samples will generate identical IL. (At least in Release builds)

    0 讨论(0)
  • 2020-12-13 08:47

    They are equivalent, apart from one being easier to read than the other one.

    Also consider the case when you want to pass the new object along to somewhere else:

    var aList = new List<Position>();
    aList.Add( new Position() { x=3, y=4 } );
    
    0 讨论(0)
  • 2020-12-13 08:51

    That is an object initialiser, and simply allows you to assign values in a single expression. Most importantly, this also works inside LINQ an for anonymous types (otherwise immutable). There is also a similar collection initialiser syntax for addi items to new collections.

    Note that there is a subtle timing issue that can be useful; with initialisers the assignments/adds all happen before the variable is assigned, which can help stop other threads seeing an incomplete object. You would otherwise need an additional variable to achieve the same result.

    0 讨论(0)
  • 2020-12-13 08:53

    Object and collection initializers, used to initialize fields on an object.

    http://msdn.microsoft.com/en-us/library/bb384062.aspx

    They produce nearly equivalent IL. Jon Skeet has the answer on what is really going on.

    0 讨论(0)
  • 2020-12-13 08:58

    Forgetting about all the IL stuff, it is just shorthand notation. What you are doing is this:

    a. In one case you are explicitly using the default constructor and then setting the two properties.

    b. In the other, you are using the new intializer syntax which implicitly makes the compiler do what you did in case a.

    IL subtelties notwithstanding, they will achieve the same thing for you.

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