I have a dozen methods in my project (C# 2.0) that look like this:
internal bool ValidateHotelStayEntity(DataRow row)
{
return (new HotelStayEntity(row)).Validate();
}
… but for different ‘entity’ classes. (Okay, not quite that trivial, I’ve simplified the code here.)
It looks like a good candidate for generics and I came up with this:
internal bool ValidateEntity<T>(DataRow row) where T : EntityBase
{
return (new T(row)).Validate();
}
And of course I get the “Cannot create an instance of the type parametrer ‘T’ because it does not have the new() constraint” error.
The problem is that these ‘entity’ classes do not have a public parameterless constructor, nor a way of adding the ‘row’ data in afterwards. And as EntityBase is part of the company framework I have no control over it (ie I can’t change it).
Is there any way around this?
Yet another way could be to involve reflection at the price of compile time checking and decreased performance:
Note that this would work even if the entities do not have a common ancestor