Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can such a nested generic method be resolved?

Tags:

c#

generics

Description

I would like to create a generic method with a single generic type input that has the return type of the generic parameter of the supplied type input.

In the context of this problem, having an instance parameter is not an option as instances would not exist in the callers context.

Example

Given the following interface:

interface IFoo<T> { }

What I am trying to achieve is something along the lines of the following improper method declarations.

TInner GetFoo<T>() where T : IFoo<TInner>;
T GetFoo<IFoo<T>>();

Which would be used like so:

class FooA : IFoo<int> { }

int foo = GetFoo<FooA>();

Question

How would such a method be declared properly (if it is even possible)?

Thanks in advance!

like image 376
Zalán Bálint Lévai Avatar asked Jan 24 '26 12:01

Zalán Bálint Lévai


1 Answers

As suggested in the comment by elgonzo, the most natural solution to your problem is a declaration of the form

TInner GetFoo<T, TInner>() where T : IFoo<TInner>

Although your idea of declaring it as TInner GetFoo<T>() where T : IFoo<TInner> is sensible, this is currently unsupported. It is akin to higher kinded parametric polymorphism a feature dearly awaited by functional programming enthusiasts.

like image 152
Samuel Vidal Avatar answered Jan 26 '26 01:01

Samuel Vidal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!