Search code examples
c#.netgenericsinheritanceabstract-class

Dotnet class method with generic return type and one generic argument


I try to make a class method when return type is generic and also one of the arguments is generic. The Return type should be generic class Result, which looks like this:

public class Result<T>
{
    public bool Success { get; set; }  
    public string Message { get; set; }
    public T? Value { get; set; }
}

The method in question is in an abstract base class:

public abstract class BaseParser
{
    protected abstract TReturn Process<T, TReturn>(HttpClient httpClient, T data) where T : class where TReturn : class;
}

This is inherited by IndexParser or another parser for different page section. I thought that I would be able to simply pass Result, but when I do this:

public class IndexParser : BaseParser
{
    protected override Result<HtmlDocument> Process<T, TReturn>(HttpClient httpClient, T data) where T : class where TReturn : class
}

I get error that returned type has to be TReturn. However when I change TReturn to Result<HtmlDocument> I get error that the method to override could not be found. I haven't found some similar examples, but not exact one, so I was unable to find what am I doing wrong.


Solution

  • The Method signature of the overriding class has to be the same the one from the base class. That means that you're Process Method has to also return TResult. The specific value you wan't in to return has to specified when you call the Method.