One easy way is to provide a factory function:
internal bool ValidateEntity<T>(DataRow row, Func<DataRow, T> factory) where T : EntityBase { return factory(row).Validate(); }
and call with:
bool valid = ValidateEntity(row, x => new Foo(x));
Remember that at this moment it is more difficult than just a challenge
bool valid = new Foo(row).Validate()
first of all...
Itโs not entirely clear what you are trying to achieve in your real context, but such a factory / provider approach can certainly be useful at other times. Please note that calling a factory delegate can also be significantly faster than using new T()
with a restriction as I wrote on my blog some time ago . Unusual in many cases, but worth knowing.
EDIT: for compatibility with .NET 2.0 you need to declare the delegate yourself, but this is easy:
public delegate TResult Func<T, TResult>(T input);
If you really use C # 2 (and not, say, C # 3, focus on .NET 2.0), you also wonโt be able to use lambda expressions, but you can still use anonymous methods:
bool valid = ValidateEntity(row, delegate(DataRow x) { return new Foo(x); });
Jon skeet
source share