Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Diference between constructor and class members initializing?

Tags:

c#

constructor

Whats the difference between using constructor when instantiating with passing arguments:

Customer Costomer1 = new Customer(100, Mark, 5000);

And doing the same but without passing anything into constructor but simply instantiating members?

Customer Costomer1 = new Customer() { ID = 100, Name = "Mark", Salary = 5000, };

Which one is better and for what situations are they are good?

Will I be correct if I will say that constructor is when more work needs to be done when instantiating an object and member initializing is for a signing values for fields and properties only?

And if Im understanding this correctly why would you use second case with members if you can use constructor?

like image 661
Ailayna Entarria Avatar asked Mar 11 '26 18:03

Ailayna Entarria


1 Answers

this is a syntax shortcut(will call default constructor)

Customer Costomer1 = new Customer() { ID = 100, Name = "Mark", Salary = 5000, }; 

equals to the follwing

Customer Costomer1 = new Customer()
Costomer1.ID = 100;
Costomer1.Name = "Mark";
Costomer1.Salary = 5000;
like image 188
Whitesmell Avatar answered Mar 13 '26 09:03

Whitesmell