1

I'd like the compiler to infer a type for me, but am unsure if it is possible, or what the best alternative might be.

I'd like to do:

public static TValue Get<TValue>(TKey key) where TValue : Mapped<TKey> { ... }

public class MyObject : Mapped<int> { ... }

And have C# infer that TKey is an int. Is there any way to do something like this? If not, what would be the best alternative?

I'd like to avoid doing something like Get<MyObject, int>(1);

Edit:

For anyone who sees this in the future, similar questions have been asked here and here

Community
  • 1
  • 1
Charles W
  • 2,262
  • 3
  • 25
  • 38
  • 4
    Seeing `TKey` doesn't give the compiler any clue as to what type `TValue` might be. – Chris Jan 09 '15 at 20:56
  • I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Jan 09 '15 at 20:58

2 Answers2

7

No, there is no way to do this in C#. What you're essentially asking for is the ability to specify some of the generic arguments explicitly and have the remainder be inferred. That's not supported in C#; generic type inference needs to be done for all or none of the generic arguments.

Servy
  • 202,030
  • 26
  • 332
  • 449
3

@Servy is correct but as it has been pointed out on the other threads, sometimes you can split types up to make things inferrable.

In this example, we specify the non-inferrable type in a class declaration and the inferrable type in the method declaration.

public static class InferHelper<TValue>
    where TValue : class
{
    public static TValue Get<TKey>(TKey key)
    {
        // do your magic here and return a value based on your key
        return default(TValue);
    }
}

and you call it like this:

var result = InferHelper<MyObject>.Get(2);
Grax32
  • 3,986
  • 1
  • 17
  • 32