Is it possible, and if so, how, to create a generic class, the parameter for which is another universal class?

Pseudo-code explaining the idea:

class Gen<T> where T : class { } // тут всё ОК class MoreGen<G> where G : Gen { } // здесь непонятно как сделать 

I would like to restrict the parameters for MoreGen only to the Gen<T> classes, so that the following code can be used:

 new MoreGen<Gen<AnyClass>>(); // Должно быть OK new MoreGen<string>(); // Нужна ошибка компиляции new MoreGen<Gen<int>>(); // Нужна ошибка компиляции 
  • Comments are not intended for extended discussion; conversation moved to chat . - PashaPash

1 answer 1

Based on the answer mentioned in the comments in English SO, a head-on solution is not possible. To achieve the desired effect, you have to add an interface:

 interface IGen {} class Gen<T> : IGen where T : class { } class MoreGen<G> where G : IGen { } public class Test { public static void Main() { new MoreGen<Gen<string>>(); // OK new MoreGen<Gen<Test>>(); // OK // new MoreGen<string>(); // no implicit reference conversion from `string' to `IGen' // new MoreGen<Gen<int>>(); // The type `int' must be a reference type } } 

Result of code execution