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

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

    In my opinion, you should first decide what makes a person a person. What are the person's properties for a person object to be correctly instantiated. What are the minimum requirements for a person.

    There should always be a constructor with the minimum requirements.

    I would only use object initializers for types that don't require any properties to be instantiated. Hence the default constructor.

    I know that object initializers are very convenient. Other mechanisms also might require an empty constructor in the object.

    But I don't think that it makes a lot of sense that you could create a Person without a name.

提交回复
热议问题