How to create a generic method that uses a generic type

I would like to write the following method

private void Foo<T, TItem>(T<TItem> param1) 

Where T must be a generic type that accepts a TItem as its generic information.

Call example:

 private void Main() { List<int> ints = new List<int>(); Foo<List, int>(ints); } 

Edit: In my case, I only needed for collections. The actual use case is that I wanted to write a method that adds something to ICollection, unfortunately ICollection does not have a .Add method that only has ICollection<T> .

I can not change the method:

 private Foo<T>(ICollection<T>) 

since with this I am losing information about what type is the actual list, which is more important to me than what type of items are in the list.

therefore, the above idea came up, which did not work.

+6
source share
3 answers

Since you only need for collections, you can describe a method like this:

 private void Foo<T, TItem>(T param1) where T: ICollection<TItem> { } 

However, in this case, you need to provide a specific generic type ( List<int> ) as the first generic parameter, you cannot use only List :

 List<int> ints = new List<int>(); Foo<List<int>, int>(ints); 
+7
source

Perhaps this may help:

Create a base class and a derived class.

 public class Item { } public class Item<T> : Item { T Value; public Item(T value) { Value = value; } } 

Then you can use it the way you want:

 public class SomewhereElse { public void Main() { List<Item> itemCollection = new List<Item>(); itemCollection.Add(new Item<int>(15)); itemCollection.Add(new Item<string>("text")); itemCollection.Add(new Item<Type>(typeof(Image))); itemCollection.Add(new Item<Exception>(new StackOverflowException())); itemCollection.Add(new Item<FormWindowState>(FormWindowState.Maximized)); // You get the point.. } } 
+1
source

It seems to me that you are trapped in the mind. There is probably a better way to solve everything that you are trying to do.

Anyway, try using Dictionary . You do not need to write a method.

 int number = 15; double dub = 15.5; Button button = new Button(); Dictionary<object, Type> typeGlossary = new Dictionary<object, Type>(); typeGlossary.Add(number, typeof(int)); typeGlossary.Add(dub, typeof(double)); typeGlossary.Add(button, typeof(Button)); 

In the end, your brain, injected into the core with a biased heart, will stop trying not to firmly fix a strongly typed C # system. We all do this at some point.

0
source

All Articles