Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
903 views
in Technique[技术] by (71.8m points)

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

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;
    private int age;

    //Omitted..
}

Should I create it to use:

New Person("name", 24);

or

New Person() { Name = "name", Age = 24 };

Is it just a matter of taste or is there a good reason to use one over the other?

I can imagine that one should only use the required fields in the constructor and optional fields not as constructor parameters but by using properties.

Am I right in that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The preferred way depends on your design.

Constructor properties are for items that your object requires in order to be correctly constructed. That is to say, any properties the object should have in order to be initialized need to be in the constructor (you don't usually want a partially intialized object after the constructor is called unless you're creating a factory or builder pattern and the constructor is hidden from all but the factory/builder).

Property intializers are best for additional configuration after a constructor that is required by your particular use case but is not required for the object to be considered initialised.

For example, you could have an object that represents a person. A person needs a name and an age to be initialised, but the address they live at is an optional configuration. So, the name and age are constructor parameters, and the address is a read/write property.

Person johnDoe = new Person("John Doe", 24) { Address = "42 Adams Street" };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...