why do I get a compiler error in the following code stating: Cannot implicty convert type SpecialNode to T even though T must derive from NodeBase as I defined in the where clause and even though SpecialNode actually derived from NodeBase?
public static T GetNode<T>() where T : NodeBase
{
if (typeof(T) == typeof(SpecialNode))
{
return ThisStaticClass.MySpecialNode; // <-- compiler error
}
if (typeof(T) == typeof(OtherSpecialNode))
{
return ThisStaticClass.MyOtherSpecialNode; // <-- compiler error
}
...
return default(T);
}
The compiler doesn’t read your
ifcheck to realize that in this particular line,Tmust beSpecialNode.You need to cast to
NodeBasefirst, like this:You need to casts because (as far as the compiler knows)
Tmight beMyOtherSpecialNode, and you cannot cast aMyOtherSpecialNodetoMySpecialNode.EDIT: You can do it with a single cast like this: