What is the preferred way of constructing objects in C#? Constructor parameters or properties?

后端 未结 11 1994
感情败类
感情败类 2020-12-15 17:26

I was wondering, what is the preferred way to construct a new object in C#?

Take a Person class:

public class Person 
{
    private string name;
             


        
11条回答
  •  盖世英雄少女心
    2020-12-15 17:54

    A few thoughts:

    1. You need public properties to use Object Initializers. So if there's something you don't want to expose, you have to initialize them by constructor parameter.

    2. If you check IL, you will find Object Initializer is not "atomic". If you write code like this (not that I recommend, just an example):

      using (p = New Person() {Name = GetName(), Age = GetAge()})
      {
        //blah, blah
      }
      

      If there's an exception in GetAge(), you will create a instance of Person in a corrupted state. Worse, you can never enter the using scope and that instance will not be disposed as you would imagine.

提交回复
热议问题