Get element type of generic list

T

Taurin

I have a method that I would like to be able to pass a generic list
(such as List<string>, List<int>, etc). I'm trying to figure out what
would be the best type of parameter to use to pass in the list and if
there is a way to find out what type of elements it is designed to
contain (even if it currently has no elements). How would I go about
doing this?
 
J

Jon Skeet [C# MVP]

Taurin said:
I have a method that I would like to be able to pass a generic list
(such as List<string>, List<int>, etc). I'm trying to figure out what
would be the best type of parameter to use to pass in the list and if
there is a way to find out what type of elements it is designed to
contain (even if it currently has no elements). How would I go about
doing this?

public void Foo<T>(List<T> list)
{
Console.WriteLine("T = {0}", typeof(T));
}

In other words, you can find out at execution time with "typeof".
 
M

Marc Gravell

Well, if you want to be able to pass a generic list, then I guess you
are talking about a generic method - i.e.

public void SomeMethod<T>(IList<T> list) {...}

In which case, the answer is typeof(T). If you mean just "a
list" (IList, not IList<T>), then a lot of the standard framework code
is based around inspected the int-indexer. For example, the code below
resolves that the list is a string-list. In the absense of a non-
object int-indexer (i.e. no indexer, or it is just typed as object),
the framework code takes the first (zeroth) element.

There is one other special case worth mentioning; the data-binding
code also respects ITypedList, which tells you about properties of the
list items - this mainly applies to flexible runtime things like
DataTableView.

Marc

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
static class Program
{
static void Main()
{
IList list = new List<string>();
PropertyInfo prop =
list.GetType().GetProperty("Item", new Type[]
{ typeof(int) });
if (prop != null)
{
Console.WriteLine(prop.PropertyType.Name);
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top