0

To demonstrate the problem I've prepared this code:

public interface IParser<T>
{
    bool TryParse(string s, out T result);
}

public sealed class TimeSpanParser : IParser<TimeSpan>
{
    public bool TryParse(string s, out TimeSpan result)
    {
        result = TimeSpan.Zero;
        return true;
    }
}

public static class ParserService
{
    public static T Parse<TParser, T>(string s)
        where TParser : IParser<T>, new()
    {
        var parser = new TParser();
        parser.TryParse(s, out var result);
        return result;
    }
}

The way to call ParserService.Parse is

var r = ParserService.Parse<TimeSpanParser, TimeSpan>("");

As you can see I need to specify TimeSpan type argument. But definition of the Parse method is

public static T Parse<TParser, T>(string s)
    where TParser : IParser<T>, new()

So in my opinion the compiler can infer T automatically by TParser. When I pass TimeSpanParser as type argument it's known that TimeSpanParser is IParser<TimeSpan> so T is TimeSpan. Is it possible to not specify T?

Like this

var r = ParserService.Parse<TimeSpanParser>("");
Maxim
  • 1,995
  • 1
  • 19
  • 24
  • The `ParserService` class is essentially pointless here, why even have it in the first place? – DavidG Sep 14 '19 at 13:19
  • I just show simplified code. In reality `ParserService.Parse` will do some complex work. I don't want to repeat it everywhere. The question about C#, please, don't think about architecture of this sample :) – Maxim Sep 14 '19 at 13:24
  • Well with a better architecture, there is no worry about generic inference. C# does not allow you to specify partial generics, you infer all types or none. – DavidG Sep 14 '19 at 13:25

0 Answers0