When we should use constructor over properties or vice versa while assigning values.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With