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.
where TSomeClass : classrestrictsTSomeClassto reference objects only, otherwise it can be any type (like value one), and you can't usenulldefaut value, it's better to useTSomeClass someClass = default(TSomeClass)- Pavel AnikhouskiSomeMethodreturnsIInterfaceand you add theIInterfacetoGenericClass's generics constraints the first line works. Not sure if that's what you're looking for though as your question is not very clear to me - nalkadefaultand added the interface to the constraints. @selvin - thanks (though not sure what you mean about SomeMethod being generic, the class is generic, not the method?), also this is a minimal example of what was causing me grief, I'm sorry I didn't make that clear in my question. - 3-14159265358979323846264GenericClass<string>, what should happen then? - Lasse V. Karlsen