Unable to cast object of type 'MyType' to type 'IMyInterface`1[System.IConvertible]'

c#

Solution

That `out` modifier you put in front of T made it covariant, but from MSDN document for `out`:

Covariance and contravariance are supported for reference types, but they are not supported for value types.

UPDATE: Sometimes (if your design allows it and you don't need the non-generic stuff outside the class) you can use a non-generic interface to solve the problem:

public interface IMyInterface
{ /*non-generic content*/}

public interface IMyInterface<out T> : IMyInterface where T : IConvertible
{/*Contents*/}

internal class MyStringClass : IMyInterface<String> {/*Contents*/}
internal class MySingleClass : IMyInterface<Single> {/*Contents*/}

static IMyInterface CreateMyObject(Type type)
{
    return (IMyInterface)Activator.CreateInstance(type);
}

Problem

I have a problem with casting my implementing classes to my generic interface. I have several internal classes inside a class that implement this interface. Then I have a method that is supposed to return any one of these classes, but the cast it contains fails for T != String. Sample: ``` public interface IMyInterface<out T> where T : IConvertible {/*Contents*/} internal class MyStringClass : IMyInterface<String> {/*Contents*/} internal class MySingleClass : IMyInterface<Single> {/*Contents*/} IMyInterface<IConvertible> CreateMyObject(Type type) { return (IMyInterface<IConvertible>)Activator.CreateInstance(type); } ``` Seeing as String is a reference type, while the others are structs, is this related? There must be something I'm missing here. (Possibly related as well: If I remove the covariance of T, casting MyStringClass fails as well.) I don't usually work with C# so this is a bit unfamiliar to me. Any explanation of why this doesn't work, as well as any pointer towards a solution is welcome. EDIT: My internal classes that implement IMyInterface are passed as `type` (typeof) EDIT2: As Alireza explained in an answer further down, making T covariant makes it not support value, types, which explains why `T = String` works, but not `T = ValueType`. I'm still stuck as to how I can make this work though...

Original source

Related problems