Reputation: 2292
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
Upvotes: 1
Views: 204
Reputation: 4069
@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);
Upvotes: 3
Reputation: 203812
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.
Upvotes: 7