I have the following code
public interface IInterface
{
}
public class GenericClass<TSomeClass>
where TSomeClass : class
{
public TSomeClass SomeMethod(TSomeClass someClass = null)
{
return SomeClass.SomeClassStaticInstance; //ERROR:Cannot implicitly convert type 'SomeClass' to 'TSomeClass'
return (TSomeClass)SomeClass.SomeClassStaticInstance; //ERROR:Cannot convert type 'SomeClass' to 'TSomeClass'
return SomeClass.SomeClassStaticInstance as TSomeClass; //Works when "where TSomeClass : class" clause added
}
}
public class SomeClass : IInterface
{
public static SomeClass SomeClassStaticInstance = new SomeClass();
}
It generates the compile time errors noted in the comments on the appropriate lines.
I would like to know why I can't just use the first line that generates an error? SomeClass
implements IInterface
but I have to mess around with the as
keyword.
I've tried changing GenericClass<TSomeClass>
to GenericClass<out TSomeClass>
but then I get another compile time error Only interface and delegate type parameters can be specified as variant.
which persists, even if i remove the where TSomeClass : class
clause.
What am I missing ... it obviously works because I can 'force it to' using the where TSomeClass : class
clause and the return SomeClass.SomeClassStaticInstance as TSomeClass;
statement!
I do actually need the where TSomeClass : class
otherwise I get yet another compile time error with TSomeClass someClass = null
... A value of type '<null>' cannot be used as a default parameter because there are no standard conversions to type 'TSomeClass'
.
So it's basically compile time errors all the way down! Thanks.