I have a method that receives a IList
. Is there any way to get the type of the items inside the IList
?
public void MiMetodo(IList miLista)
{
}
I have a class to which you can associate a IList
. You can also add a function NuevoItem
to add new items. I would like to be able to add items with the default parameterless constructor in case the user of my class does not assign a value to the function NuevoItem
.
I add an example, because it seems I have not been clear with my question. If I receive a IList<Int32>
, I want to know the type of the item, that is, I need to get the Int32
.
How can I get the Type of the items that are inside the IList
one I receive by parameter? I'd know if I had a IList<T>
, but I can't change my API , since we can receive any type of collection, not just IList<T>
. The only restriction, although not enforced by code, is that all items in the collections we receive are of the same type.
If the type of the object you pass to
miLista
is generic, which you can check withmiLista.GetType().IsGenericType
you can get the type of the item using the propertyGenericTypeArguments
In this case it
.GenericTypeArguments
returns aType[]
, where the first element will be theType
one you are looking for.In the case of not being generic, one cannot properly speak of an element type, since each element in a non-generic array can be any
Object
.In this case you can assume what you need for example:
If there is at least one element, assume that
Type
of the first element as the type of theIList
miLista[0].GetType();
If there is at least one element, iterate through the ,
IList
and if you are sure that all elements are of the same type, assume that the type of the first element is the type of theIList
.miLista[0].GetType();
If there are multiple elements of different types, assume
Object
null
If you want to be sure of all possible cases, this code snippet can help:
If I understand correctly you need to know the type of the list to be able to add new items at runtime via Activator:
And for that you need to know the type of objects that your list brings; then you need to get the type of the Item property of your list, in other words:
In your specific case it would be something like this:
The full example:
Example link in DotNetFiddle:
https://dotnetfiddle.net/tnTLcw
Finally:
You will be able to know the real type of the items in your list as long as they are not of type Object.
Have you tried a simple
Carlos's comment is important:
You do NOT need reflection to achieve this.
In that case, you are supported by a business rule , this will suffice to achieve your goal:
implementation
full demo
And the proper way to use it can be like what you see below in this demo where I test with various types to ensure all possible scenarios
the code
output