Lets say I have an interface passed to my method:
public void AlphaToChar(iList _blah)
{
}
Out of IList I want to extract it’s members Type and use its type to create other Arrays or Lists in the method. See example below.
The “List = new List();” part doesn’t work because, as I assume it’s a type variable, not the actual type.
Any way around this ? How can I accomplish this and create a new collection of an extracted Type?
Type[] listTypes = list.GetType().GetGenericArguments();
Type listType = null;
if (listTypes.Length>0)
{
listType = listTypes[0];
}
List<listType> = new List<listType>();
Thank you.
You can do the
List<>construction using the following:But it’s only going to work if you are using generic lists. The example you gave was using a regular
IList. You would have to change your method signature to use a genericIList<>:Or make it even more generic:
Without doing so, you should know what your
IListis going to contain and you wouldn’t have to use reflection to figure out what its elements types are.