I'm creating a factory method that determines the object to return based on the generic type in the method call
public IDbStrategy<T> GetDefaultStrategy<T>()
{
return typeof(T).IsAssignableFrom(typeof(DbModel))
? new DefaultModelDbStrategy<T>()
: new DefaultDbStrategy<T>();
}
the DefaultModelDbStrategy
as a type constraint of where T : DbModel
but the DefaultDbStrategy
does not. I am getting a compiler error when trying to use T
as the generic type for DefaultModelDbStrategy
because the compiler doesn't know that T
is a DbModel
. Is there a way to ensure my compiler that the generic argument passed in does indeed derive from DbModel
as the reflection statement above asserts?
Thanks
CodePudding user response:
Not without reflection. Because T
is statically resolved at compile time, the compiler would need to instantiate type DefaultModelDbStrategy<object>
(if T is object
), but this is an illegal type. The types used within a method need to be resolved when the method is JITed, and not only when a particular line is executed.
There's a workaround using reflection though: You can do
(IDbStrategy<T>)Activator.CreateInstance(typeof(DefaultModelDbStrategy<>).MakeGenericType(typeof(T)));
This creates an instance of DefaultModelDbStrategy, with the given T. It will throw a runtime error if T doesn't satisfy the constraints.