Question:
I have a method that receives an IList
. Is there a way to get the type of the items that are inside the IList
?
public void MiMetodo(IList miLista)
{
}
I have a class to which you can associate an IList
. You can also add a NuevoItem
function 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 NuevoItem
function.
I add an example, because it seems I have not been clear with my question. If I get an 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
that I receive by parameter? I would know how to do it if I had an IList<T>
, but I can't change my API as we can receive any kind 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.
Answer:
If the type of the object you pass to miLista
is generic, which you can check with miLista.GetType().IsGenericType
you can get the item type using the GenericTypeArguments
property
Type tipo = miLista.GetType().GenericTypeArguments[0];
In this case .GenericTypeArguments
returns a Type[]
, where the first element will be the Type
you are looking for.
In the case of not being generic, it is not possible to speak of an element type properly 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 the
Type
of the first element as the type of theIList
miLista[0].GetType();
-
If there is at least one element, go through the
IList
and if you are sure that all the 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
- If there are no elements, there is nothing left but to assume
null
If you want to be sure of all possible cases, this code fragment can help you:
Type tipoDeItemDeLaLista;
var tipoLista = miLista.GetType();
if (tipoLista.IsGenericType)
{
tipoDeItemDeLaLista = tipoLista.GenericTypeArguments[0];
}
else
{
if (miLista.Count == 0)
{
throw new Exception("No se puede hablar de tipo de elemento si miLista esta vacía");
}
var tipoDelPrimerElemento = miLista[0].GetType();
foreach (var elemento in miLista)
{
if (elemento.GetType() != tipoDelPrimerElemento)
{
throw new Exception("No se puede hablar de tipo de elemento si los tipos son diferentes entre sí");
}
}
tipoDeItemDeLaLista = tipoDelPrimerElemento;
}