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
The compiler doesn't read your if
check to realize that in this particular line, T
must be SpecialNode
.
You need to cast to NodeBase
first, like this:
return (T)(NodeBase)MySpecialNode;
You need to casts because (as far as the compiler knows) T
might be MyOtherSpecialNode
, and you cannot cast a MyOtherSpecialNode
to MySpecialNode
.
EDIT: You can do it with a single cast like this:
NodeBase retVal;
if (typeof(T) == typeof(SpecialNode))
retVal = MySpecialNode;
else if (typeof(T) == typeof(OtherSpecialNode))
retVal = MyOtherSpecialNode;
return (T)retVal;