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

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

提交回复
热议问题