C# generic list <T> how to get the type of T? [duplicate]
Asked Answered
E

4

157

I'm working on a reflection project, and now I'm stuck.

If I have an object of myclass that can hold a List<SomeClass>, does anyone know how to get the type as in the code below if the property myclass.SomList is empty?

List<myclass> myList = dataGenerator.getMyClasses();
lbxObjects.ItemsSource = myList; 
lbxObjects.SelectionChanged += lbxObjects_SelectionChanged;

private void lbxObjects_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Reflect();
}

Private void Reflect()
{
    foreach (PropertyInfo pi in lbxObjects.SelectedItem.GetType().GetProperties())
    {
        switch (pi.PropertyType.Name.ToLower())
        {
            case "list`1":
            {           
                // This works if the List<T> contains one or more elements.
                Type tTemp = GetGenericType(pi.GetValue(lbxObjects.SelectedItem, null));

                // but how is it possible to get the Type if the value is null? 
                // I need to be able to create a new object of the type the generic list expect. 
                // Type type = pi.getType?? // how to get the Type of the class inside List<T>?
                break;
            }
        }
    }
}

private Type GetGenericType(object obj)
{
    if (obj != null)
    {
        Type t = obj.GetType();
        if (t.IsGenericType)
        {
            Type[] at = t.GetGenericArguments();
            t = at.First<Type>();
        } 
        return t;
    }
    else
    {
        return null;
    }
}
Electromotor answered 25/6, 2009 at 12:57 Comment(0)
B
286
Type type = pi.PropertyType;
if(type.IsGenericType && type.GetGenericTypeDefinition()
        == typeof(List<>))
{
    Type itemType = type.GetGenericArguments()[0]; // use this...
}

More generally, to support any IList<T>, you need to check the interfaces:

foreach (Type interfaceType in type.GetInterfaces())
{
    if (interfaceType.IsGenericType &&
        interfaceType.GetGenericTypeDefinition()
        == typeof(IList<>))
    {
        Type itemType = type.GetGenericArguments()[0];
        // do something...
        break;
    }
}
Baptize answered 25/6, 2009 at 13:2 Comment(4)
shouldn't it be Type itemType = interfaceType.GetGenericArguments()[0];Hamil
Amusingly, the second example fails with, say IList<int>. Fix below https://mcmap.net/q/32870/-c-generic-list-lt-t-gt-how-to-get-the-type-of-t-duplicateTernan
I know that the answer is very old, but I try to understand the following: 'GetGenericArguments()[0];' why is there the 0? Is there only always one item in the Type[] ?Teem
Because the call GetGenericArguments() returns an array. msdn.microsoft.com/en-us/library/… A List will only have one type. A dictionary would have two for example.Stratton
T
24

Given an object which I suspect to be some kind of IList<>, how can I determine of what it's an IList<>?

Here's the gutsy solution. It assumes you have the actual object to test (rather than a Type).

public static Type ListOfWhat(Object list)
{
    return ListOfWhat2((dynamic)list);
}

private static Type ListOfWhat2<T>(IList<T> list)
{
    return typeof(T);
}

Example usage:

object value = new ObservableCollection<DateTime>();
ListOfWhat(value).Dump();

Prints

typeof(DateTime)
Ternan answered 28/11, 2012 at 15:33 Comment(4)
-1: Why IList<T> instead of IEnumerable<T>? Why dynamic?Roundelay
Did I misunderstand OP's question? The detail was unclear, so I answered the question in the title.Ternan
You sir, are a Wizard! I have been banging my head trying to solve an issue with a dynamic parser with a generic data structure (that can deal with singular types and Lists) and this got me on the right track.Marmion
Great example of 'dynamic' usageAlternately
W
12

Marc's answer is the approach I use for this, but for simplicity (and a friendlier API?) you can define a property in the collection base class if you have one such as:

public abstract class CollectionBase<T> : IList<T>
{
   ...

   public Type ElementType
   {
      get
      {
         return typeof(T);
      }
   }
}

I have found this approach useful, and is easy to understand for any newcomers to generics.

Warm answered 25/6, 2009 at 13:52 Comment(3)
I wanted to use this approach but then i realized i will have to have the list instance in order to determine element type, which i will not always have.Hamil
you can make the property static. Like "public static Type ElementType" ... then you get at it as "var t = CollectionBase<int>.ElementType;" ... you will not need an instance variableHelbonia
True. Static allows you to work with a class without an existing object. I find this approach easier to work with. Sure, you need to store additional information in your objects but at least you spare yourself from this cascade-call in the approved answer.Mackay
T
10

Given an object which I suspect to be some kind of IList<>, how can I determine of what it's an IList<>?

Here's a reliable solution. My apologies for length - C#'s introspection API makes this suprisingly difficult.

/// <summary>
/// Test if a type implements IList of T, and if so, determine T.
/// </summary>
public static bool TryListOfWhat(Type type, out Type innerType)
{
    Contract.Requires(type != null);

    var interfaceTest = new Func<Type, Type>(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>) ? i.GetGenericArguments().Single() : null);

    innerType = interfaceTest(type);
    if (innerType != null)
    {
        return true;
    }

    foreach (var i in type.GetInterfaces())
    {
        innerType = interfaceTest(i);
        if (innerType != null)
        {
            return true;
        }
    }

    return false;
}

Example usage:

    object value = new ObservableCollection<int>();
Type innerType;
TryListOfWhat(value.GetType(), out innerType).Dump();
innerType.Dump();

Returns

True
typeof(Int32)
Ternan answered 28/11, 2012 at 15:20 Comment(1)
I don't see any other result as Marcs method (also with marcs i get Int32)Strobila

© 2022 - 2024 — McMap. All rights reserved.