I’m writing generic methods and I am confused as to why the following code snippet throws a syntax error:
public abstract class Parent
{
public virtual T MyMethod<T>() where T : Parent, new()
{
return this;
}
}
This method is constrained to returning types that are either Parent
or types derived from Parent
. Since this class is abstract, by returning this
, the method is obviously going to return some class that inherits from Parent
, yet there is a syntax warning saying “Cannot implicitly convert type ‘Parent’ to ‘T’. An explicit conversion exists (are you missing a cast?)”
Can someone explain why this is the case and how it can be fixed?