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

后端 未结 11 1827
感情败类
感情败类 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:48

    I tend to prefer a very simple constructor with property intializers. I find it leads to more explicit code. The only data I would pass to the constructor is information that I do not want the user of my class to alter once the class is created.

    0 讨论(0)
  • 2020-12-15 17:48

    For settings the properties manually, they would have to be declared public, and you may want the class members to be private. In which case the constructor is the way to go, or write methods to get/set them or use an accessor.

    0 讨论(0)
  • 2020-12-15 17:50

    The second way is just syntactic sugar for setting the properties manually:

    Person p = new Person();
    p.Name = "name";
    p.Age = 24;
    

    You're also not depending on the constructor which may not initalize all the properties you want to set.

    If your class has a constructor which requires these two parameters, you don't get around to explicitly call that constructor.

    0 讨论(0)
  • 2020-12-15 17:52

    Setting the values in the constructor, makes those properties mandatory, so this means you cannot create a new instance, without settings those properties. In some situations this is preferable, in other situations this is not prefferable.

    0 讨论(0)
  • 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.

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