I am trying to implement a generic method but need to cast an object of one generic type (T1 - defined on the class) to another generic type (T2 defined on the method). Other than defining T2 on the class (which I'd rather not because it won't always be needed), is there a way of achieving this?
I'm after something like this:
public class SomeClass<T1>
{
public void SomeMethod<T2>(T1 someParameter) where T1 : T2
{
T2 someVariable = (T2) someParameter;
}
}
It seems the constraint will only work the wrong way around, that is where T2:T1
works (but is obviously wrong for my purpose), but where T1:T2
doesn't.
update The reason I need to cast T1 to T2, is I use the result in a database insert method which uses reflection on the Interface to determine what columns to insert into. The interface is used to prevent trying to insert into computed columns for instance. So T2 would be this interface whereas T1 would be an original object (which would have more fields). Hence casting T2:T1 would not be correct.