How to make safe cast using generics in C#?

Posted by TN on Stack Overflow See other posts from Stack Overflow or by TN
Published on 2010-03-30T21:58:30Z Indexed on 2010/03/30 22:03 UTC
Read the original article Hit count: 326

I want to implement a generic method on a generic class which would allow to cast safely, see example:

public class Foo<T> : IEnumerable<T>
{
    ...
    public IEnumerable<R> SafeCast<R>()
        where T : R
    {
        return this.Select(item => (R)item);
    }
}

However, the compiler tells me that Foo<T>.SafeCast<R>() does not define parameter 'T'. I understand this message that I cannot specify a constraint on T in the method since it is not defined in the method. But how can I specify an inverse constraint?

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics