Constructor is a special type of method which will automatically get invoked when object is initialized.
Main uses of constructor: –
Initializing data with default (or some specified values) values.
I think we can achieve the same thing with functions also then why constructor?
Functions define the behavior of a class (or object). It may use the existing data and may modify them.
There is a difference between initializing and assigning. Initializing means setting the initial values (at the time of creation) whereas assigning may means changing some existing value also. For Initializing we use constructor. It’s a best practice not a fixed rule.
What is the difference between property and Variable in terms of usage?
Variable contains data. They can define as a temporary memory location which holds data. properties are encapsulation over data and thus protects data. Internally when we create properties it gets converted to one variable and two functions (one set and one get).
Let’s say I want to create a function having only one parameter. Can I use property instead of function for this purpose?
Yes you can but, it’s not preferred. Properties are meant to be data and functions for behavior. Again it’s a best practice.
Hope you enjoyed reading this and learned something. Your comments and votes are always welcome.
Also see following .NET interview questions video on private constructor in C#: –