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

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

    I always work on the basis that you should pass values to a constructor which are mandatory for that object to exist in a valid state.

    In you example you could say that new person cannot exists without an age so that should be passed in to the contructor.

    If you work on the basis that an object should model a real work entity then that determines the minimum necessary to make any object valid - whether you set those as default values or by passing values in via the constructor.

提交回复
热议问题