tags:

views:

37

answers:

2

I have a generic method like this (simplified version):

public static TResult PartialInference<T, TResult>(Func<T, TResult> action, object param)
{
    return action((T)param);
}

In the above, param is of type object on purpose. This is part of the requirement.

When I fill in the types, I can call it like this:

var test1 = PartialInference<string, bool>(
    p => p.EndsWith("!"), "Hello world!"
);

However, I'd like to use type inference. Preferably, I would like to write this:

var test2 = PartialInference<string>(
    p => p.EndsWith("!"), "Hello world!"
);

But this does not compile. The best I came up with is this:

var test3 = PartialInference(
    (string p) => p.EndsWith("!"), "Hello world!"
);

The reason I would like to have this as a type parameter and still have the correctly typed return type is because my actual calls look something like this:

var list1 = ComponentProvider.Perform(
    (ITruckSchedule_StaffRepository p) => p.GetAllForTruckSchedule(this)
)

Which is very ugly and I would love to write as something like this:

var list2 = ComponentProvider.Perform<ITruckSchedule_StaffRepository>(
    p => p.GetAllForTruckSchedule(this)
)
+1  A: 

What you are trying to achieve is not possible. You need to specify both generic arguments or none of the them if inference is possible.

Darin Dimitrov
Any ideas for a rewrite of the method that would still get rid of the ugly typing of the `p` parameter?
Pieter
I think the last version you had is not as bad: you just need an additional generic parameter for the return type.
Darin Dimitrov
That's the whole point. The type is there, the `GetAllForTruckSchedule` has a return type, and I do not want to specify this. This method is used e.g. in Linq queries and I would like to have inference do it's work as much as possible. `var` all the way :).
Pieter
+3  A: 

You can split t into a generic method on a generic type:

class Foo<TOuter> {
    public static void Bar<TInner>(TInner arg) {...}
}
...
int x = 1;
Foo<string>.Bar(x);

Here the int is inferred but the string is explicit.

Marc Gravell
Thanks, that's it.
Pieter