0

This is a purely aesthetic thing, but I think it is worth asking nonetheless. In the following code:

interface IGiveResult<TResult>
{
    TResult GetResult();
}

static class ResultGetter
{
    GetResultFrom<TResultGiver, TResult>(TResultGiver giver) where TResultGiver : IGiveResult<TResult>
    {
        return giver.GetResult();
    }
}

To call GetResultFrom, I need to specify both type parameters like this:

ResultGetter.GetResultFrom<SomeGiverType, SomeResultType>(someGiverInstance);

However, I would like to call is like this:

ResultGetter.GetResultFrom<SomeGiverType>(someGiverInstance);

After all, the compiler has all the information neccessary to infer the second generic type. However, this does not compile. Is it possible to change this code, so that one doesn't have to specify the result type?

vidmartin
  • 82
  • 5
  • Reopened as the approach in https://stackoverflow.com/questions/10719557 won't actually work here, I *think*. The approach in that question would lead to code of `ResultGetter.GetResultFrom(someGiverInstance)` but I don't *think* that will help in this case. I'm not entirely sure though, and we don't have a complete example to work from (that would make it easy to check). – Jon Skeet Jul 26 '21 at 18:33
  • 1
    Type inference is all or nothing. You either let it infer all of the types or you explicitly provide all of the types – Damien_The_Unbeliever Jul 26 '21 at 18:33
  • Also, be very aware that "I can see the obvious substitutions" doesn't imply "a compiler can be built to apply appropriate substitutions" to reach the same conclusions you do. – Damien_The_Unbeliever Jul 26 '21 at 18:36
  • 1
    _"Is it possible"_ is very vague...and personally, I think Jon's answer _could_ work given the information you've provided here (i.e. very little). If you are stuck with the signature you have, then no...type inference works from the arguments, and doesn't do "partial inference". If you are willing to change the way the actual types you're using are declared, the duplicates offer a number of alternatives that could work for you. – Peter Duniho Jul 26 '21 at 18:37
  • The example is probably reduced/shortened. Type param `TResultGiver` seems redundant since you don't need to to know the exact type of `TResultGiver` to invoke GetResult and return TResult. `GetResultFrom(IGiveResult giver)` seems an adequate signature and thhen it could easily be inferred. Actually the whole static class seems a redundant wrapper since you could call GetResult straight away from `giver`. But likely is due to the show case, not real code. – lidqy Jul 26 '21 at 18:58

0 Answers0