Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor or properties: which one is the better choice while assigning values

When we should use constructor over properties or vice versa while assigning values.

like image 232
user498432 Avatar asked Nov 13 '10 18:11

user498432


People also ask

What is the difference between a property and a constructor?

Constructors have the same name as the class or struct, and they usually initialize the data members of the new object. Properties enable a class to store, setting and expose values needed for the object. You should create to help in the behavior for the class.

Why do we need properties in C#?

Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code. A get property accessor is used to return the property value, and a set property accessor is used to assign a new value.

What is constructor in C sharp?

In C#, constructor is a special method which is invoked automatically at the time of object creation. It is used to initialize the data members of new object generally. The constructor in C# has the same name as class or struct. There can be two types of constructors in C#. Default constructor.

Can constructors be less parameters?

Parameter-less ConstructorWhen a constructor is declared without any parameter or argument, then it is called a parameter-less constructor. A parameter-less constructor works like a default constructor and this constructor can contain statements, or it can be empty.


1 Answers

A constructor is a very convenient and powerful type of contract - a way to require consumers to provide certain information before they can even use your object. So for information that is necessary for the instance to function properly, use constructor parameters. This is the underlying concept of dependency injection - anything you depend on to do your job, must be injected (provided) to you before you begin.

Properties can represent an interesting problem. In general, experience has taught me that wherever possible, properties should be read-only and objects should generally be as externally immutable as possible. Adding a public setter to a property is a multiplier of complexity for your class. There are of course always types of objects - entities are a good example - where setters make sense. But for most objects, the pattern of "write-to via constructor" / "read-from via properties" for state has vastly reduced complexity and bug risks in the applications I've been responsible for.

like image 126
Rex M Avatar answered Sep 25 '22 18:09

Rex M