I’ve got this repository method:
public virtual T Get<T>(object primaryKey) where T : IDalRecord, new() //note: can't change the where clause
{
return Record<T>.FetchByID(primaryKey); // how? <--compile time error
}
defined in a 3-rd party assembly:
public class Record<T> where T : Record<T>, IRecordBase, new()
{
public static Record<T> FetchByID(object primaryKey) { /*...*/ }
}
My T and the 3-rd party T are not directly compatible, however my objects that inherit from Record<T> also also implement IDalRecord, so i can cast the object instance to any of these type.
But how can i tell the compiler to “cast” (IDalRecord)T to (Record<T>)T?
There is no way to tell the compiler that
Tactually inherits fromRecord<T>. The reason is simple: because it is not true, generally speaking. Indeed, yourGetmethod may, theoretically, be called with any argument, not necessarily that inheriting fromRecord<T>.The fact that
Tdoes, in fact, inherit fromRecord<T>only becomes known at runtime, when your method is actually called. Therefore, necessary checks and constructs must take place at that same moment.Keep in mind that is it entirely possible (and even encouraged) to cache those
Helper<T>objects for performance.You can also just use old dumb reflection: find the method FetchByID by name and call it dynamically. But that would cause enormous performance penalty.