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...