I have the following classes:
Defect– represents a type of data that can be found in a databaseFilterQuery– provides a way of querying the database by setting simple Boolean filters
Both Defect and FilterQuery implement the same interface: IDefectProperties. This interface specifies particular fields that are in the database. Different classes have methods that return lists of Defect instances. With FilterQuery, you specify some filters for the particular properties implemented as part of IDefectProperties, and then you run the query and get back a list of Defect instances.
My problem is that I end up implementing some properties exactly the same in FilterQuery and Defect. The two are inherently different classes, they just share some of the same properties. For example:
public DateTime SubmitDateAsDate
{
get { return DateTime.Parse(SubmitDate); }
set { SubmitDate = value.ToString(); }
}
This is a property required by IDefectProperties that depends on a different property, SubmitDate, which returns a string instead of a DateTime. Now SubmitDate is implemented differently in Defect and FilterQuery, but SubmitDateAsDate is exactly the same. Is there a way that I can define SubmitDateAsDate in only place, but both Defect and FilterQuery provide it as a property? FilterQuery and Defect already inherit from two different classes, and it wouldn’t make sense for them to share an ancestor anyway, I think. I am open to suggestions as to my design here as well.
If inheritance isn’t appropriate and you want to reuse code, you have to use either composition (probably overkill for the simple case you’ve described) or extension methods.
Extension methods are a great way to simulate multiple inheritance in C#, though there are no extension properties (“maybe someday” says Eric Lippert). If you’re willing to give up property semantics, you could do this: