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

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

    The real issue comes when you pass the object through tiers/layers. For example you create a person object and pass through a webservice. The webservice at somepoint tries to deserialize and tries to instantiate and then you might get an error if there is a paramter required for constructors! as webservices first creates an object and then assigns values.

    So I would prefer a parameterless contructor if it is a datamodel (POCO sort of) that needs to pass through tiers.

    For other reasons contructor parameter is the best way(for mandatory fields). Especially when providing the class as an iterface to external objects or assemblies.

提交回复
热议问题