Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to cast type parameter?

Tags:

c#

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
{
    // ...
}
like image 646
homu Avatar asked May 01 '15 06:05

homu


1 Answers

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
}
like image 111
Jon Skeet Avatar answered Sep 18 '22 18:09

Jon Skeet