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.
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.
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.
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