Passing a generic generic parameter in C #

I experimented a bit with generators in C #, and I had a problem when I want to pass a generic type as a constrained type parameter to implement a generic interface whose type I don't know.

Here is my example:

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication3 { class Program { interface IGenericCollection<T> { IEnumerable<T> Items { get; set; } } abstract class GenericCollection<T> : IGenericCollection<T> { public IEnumerable<T> Items { get; set; } } //This class holds a generic collection but i have to ensure this class //implements my IGenericCollection interface. The problem here is that //i dont know which type TGenericCollection is using and so i am unable to //pass this information to the constraint. class CollectionOwner<TGenericCollection> where TGenericCollection : IGenericCollection< dont know ... > { protected TGenericCollection theCollection = default(TGenericCollection); } static void Main(string[] args) { } } } 

I read a few posts here and everyone told me that this is not possible due to C # and CLR limitations. But what would be the right way to do this?

+4
source share
4 answers

Perhaps you need another parameter of the type:

 class CollectionOwner<TGenericCollection, T2> where TGenericCollection : IGenericCollection<T2> where T2 : class { protected TGenericCollection theCollection = default(TGenericCollection); } 

Does this fit you?

+1
source

I don’t think there is a problem there, just add another general parameter to the Owner class:

  class CollectionOwner<T,TGenericCollection> where TGenericCollection : IGenericCollection<T> { protected TGenericCollection theCollection = default(TGenericCollection); } 
+1
source

You can add a second general parameter to the implementation class. The following is an example of the static method Example .

 public interface ITest<T> { T GetValue(); } public class Test<T, U> where T : ITest<U> { public U GetValue(T input) { return input.GetValue(); } } public class Impl : ITest<string> { public string GetValue() { return "yay!"; } public static void Example() { Test<Impl, string> val = new Test<Impl,string>(); string result = val.GetValue(new Impl()); } } 
+1
source

Using the second general parameter is option 4 that I already wanted to use, but what about this

  abstract class GenericCollection<T> : IGenericCollection<T> { public IEnumerable<T> Items { get; set; } } class ConcreteCollection : GenericCollection<string> { } static void Main(string[] args) { // will constraint fail here ? CollectionOwner<int,ConcreteCollection> o = new CollectionOwner(int, ConcreteCollection); } 
0
source