Now that I'm back from the funeral and back in action I thought I'd create a post that hopefully will prove to be helpful to someone out there in the cyberworld seeking guidance. This one's regarding constructors.
A while back, while dabbling in the realm of constructors, I came upon a little tidbit that I haven't seen documented - not that it isn't documented, I just didn't go searching for it. If you have a class (or a struct) in which you have several overloads on the constructor where each constructor does a lot of the same work, you can save yourself some headache. In a fashion similar to how you call the base class's constructor, you can call another constructor by simply calling the this(...) method. So instead of having code that resembles the following:
public sealed class Customer {
private string _name;
private DateTime _startDate;
public Customer(string name) {
_name = name;
_startDate = DateTime.Now();
}
public Customer(string name, DateTime startDate) {
_name = name;
_startDate = startDate;
}
}
you have code that looks like this:
public sealed class Customer {
private string _name;
private DateTime _startDate;
public Customer(string name) : this(name, DateTime.Now()) { }
public Customer(string name, DateTime startDate) {
_name = name;
_startDate = startDate;
}
}
Granted, this is a simplistic case that doesn't really do much, but it saves the burden of repeating code unnecessarily and give you the benefit of having a single working constructor (or at least just a few) which greatly simplifies the readability of your code.