Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# constructors

Could someone advice me on what approach to take when writing C# constructors?

In other languages, like C++, everything is fine - you usually don't make the internal fields visible and provide getters / setters for them.

This means, you could provide your class with constructors, which initialize all / some of your local members and be happy.


C#, however, has properties, which allows us to write something like:

Class x = new Class { Field1 = new Field1 ...., Field2 = new Field2 }

This allows chaining for the object construction and, as I assume, can remove a lot of constructors, which would be required if we didn't have properties.

Combining this with default values for properties, as I assume, we can completely get rid of non-specialized constructors, which actually do some work.

Now - is it okay to remove redundant constructors and allow object constructing via field initializing?

What are the drawbacks of this approach? Could someone give general recommendations about combining the usage of fields and constructors, some rules of thumb, probably?

Thank you.

like image 723
Yippie-Ki-Yay Avatar asked Mar 30 '11 12:03

Yippie-Ki-Yay


2 Answers

My own rule of thumb is simple: If something is required to completely construct the object, it should be a ctor parameter.

A good example is one of the Stream helper objects like StreamReader or BinaryReader. They cannot function without an associated Stream object, so that must be specified in the constructor.

like image 55
Tergiver Avatar answered Nov 15 '22 09:11

Tergiver


In my opinion, there is nothing wrong with having what you term as redundant constructors. If it makes enough sense for you to want to define a constructor, it is probably because there's a genuine need to do it that way.

like image 31
ZombieSheep Avatar answered Nov 15 '22 08:11

ZombieSheep