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

2
  • 4
    Seeing TKey doesn't give the compiler any clue as to what type TValue might be. Commented Jan 9, 2015 at 20:56
  • I have edited your title. Please see, "Should questions include “tags” in their titles?", where the consensus is "no, they should not". Commented Jan 9, 2015 at 20:58

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.