What's the difference between an object initializer and a constructor?

后端 未结 7 1309
温柔的废话
温柔的废话 2020-11-22 12:23

What are the differences between the two and when would you use an \"object initializer\" over a \"constructor\" and vice-versa? I\'m working with C#, if that matters. Als

相关标签:
7条回答
  • 2020-11-22 12:46

    When you do

    Person p = new Person { Name = "a", Age = 23 };
    

    this is what an object initializer essentially does:

    Person tmp = new Person(); //creates temp object calling default constructor
    tmp.Name = "a";
    tmp.Age = 23;
    p = tmp;
    

    Now this facilitates behaviour like this. Knowing how object initializers work is important.

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