Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial type inference

Tags:

c#

generics

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)
)
like image 604
Pieter van Ginkel Avatar asked Oct 23 '10 10:10

Pieter van Ginkel


People also ask

What is partial type?

The Partial type in TypeScript is a utility type which does the opposite of Required. It sets all properties in a type to optional.

What is ReturnType TypeScript?

The ReturnType in TypeScript is a utility type which is quite similar to the Parameters Type. It let's you take the return output of a function, and construct a type based off it.


1 Answers

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.

like image 111
Marc Gravell Avatar answered Oct 09 '22 21:10

Marc Gravell