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.
Field1
is a property. – Rosalinarosalind