Can I use type parameter as implementing specific interface at Runtime without Reflection? The following pseudocode is what I want to do.
void Run1<T> ()
{
// ...
if (typeof (IEnumerable).IsAssignableFrom (typeof (T)) {
Run2<T implementing IEnumerable> (); // <- use T as implementing IEnumerable
}
// ...
}
void Run2<T> () where T : IEnumerable
{
// ...
}
No, I don't believe there's a simple way you can do that.
If you're in control of all the code, you could have a public version of Run2
with the constraint, but a private implementation of Run2
without the constraint, which you call from Run1
:
public void Run1<T>()
{
// ...
if (typeof(IEnumerable).IsAssignableFrom(typeof(T))
{
Run2Impl<T>();
}
// ...
}
public void Run2<T>() where T : IEnumerable
{
Run2Impl<T>();
}
private void Run2Impl<T>()
{
// Need to cast any values of T to IEnumerable here
}
See more on this question at Stackoverflow