Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested generics <T1<T2>>

Tags:

c#

generics

Why it is impossible to write something like this:

T1<T2> Method<T1, T2>(T1<T2> genericValue) { ... }

For example, I want to write an extension method which accepts a generic object, containing a generic colletion:

Container<CT<T>> ExtensionMethod<CT, T>(Container<CT<T>> value) { ... }

where CT can be Array, List or any other collection type and T is any type. But Compiler says "Type parameter T1 does not have type parameters".

Is there any workaround for that?

like image 926
Alex Butenko Avatar asked Jun 28 '17 10:06

Alex Butenko


1 Answers

This is not possible. Your generic has to compile for any T. So if you make any assumption about T other than it being object you have to add constraints with the where keyword.

This constraints system is not very complex. You cannot add a constraint asking for T to be a class with exactly one generic type parameter. So what you want to do is impossible with the current toolset.

You would need to ask Microsoft why they did not implement it, but it appears they saw not enough business value.

Maybe you could ask a question how to implement something, without breaking it down to generics. It seems you may have an XY Problem.

like image 69
nvoigt Avatar answered Sep 23 '22 03:09

nvoigt