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.
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.
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.
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.
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With