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

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

    It really depends on the scenario. The property approach has a lot of convenience, in that you don't have to duplicate the assignments in the constructor. Furthermore, most data-binding scenarios like to be able to create new objects, for which they usually use the parameterless constructor, so that is a big advantage.

    However, for immutable types, the constructor approach is the only sensible option. Interestingly (perhaps) the named/optional parameters in C# 4.0 allow something similar to object initalizers for immutable types - see here.

    The constructor approach is also very popular for Inversion of Control frameworks, as it clearly advertises what that class needs in order to function.

    You may need to mix and match, but usually more property-style than constructor-style.

提交回复
热议问题