Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the underlying type of an IList item?

Tags:

c#

reflection

I have a method that receives an IList. Is there a way to get the Type of the items of the IList?

public void MyMethod(IList myList)
{
}

I have a class that you can associate an IList to, you can also add a NewItem function, but I would like to be able to add items with the default empty constructor in case the user didn't set the NewItem function.

How can I get the Type of the underlying items? I would know how to do it if it was an IList<T>, but I can't change the API, because I can receive any kind of collection that implements IList, only restriction, that is not enforced by code, is that all the items in the collections we receive are of the same type.

like image 603
Dzyann Avatar asked Dec 10 '15 21:12

Dzyann


People also ask

What is IList type in C#?

In C# IList interface is an interface that belongs to the collection module where we can access each element by index. Or we can say that it is a collection of objects that are used to access each element individually with the help of an index. It is of both generic and non-generic types.

Should I use list or IList C#?

List is used whenever you just want a generic list where you specify object type in it and that's it. IList on the other hand is an Interface.

What does IList mean?

The IList interface implemented from two interfaces and they are ICollection and IEnumerable. List and IList are used to denote a set of objects. They can store objects of integers, strings, etc. There are methods to insert, remove elements, search and sort elements of a List or IList.

How do I initialize an IList?

IList<ListItem> allFaqs = new List<ListItem>(); and it should compile. You'll obviously have to change the rest of your code to suit too. IList<ListItem> test = new ListItem[5]; IList<ListItem> test = new ObservableCollection<ListItem>(allFaqs);


1 Answers

Since it's an IList, you'd first have to check if it is actually generic:

if (list.GetType().IsGenericType)
      Console.WriteLine($"Is generic collection of {list.GetType().GenericTypeArguments[0]}");
else
      Console.WriteLine("Is not generic");

For example, using

IList list = new List<string>();

would give Is generic collection of System.String, and

IList list = new ArrayList();

would give Is not generic

like image 153
Jonesopolis Avatar answered Oct 06 '22 17:10

Jonesopolis