locked
Getting Underlying type of generic collection by relection? RRS feed

  • Question

  • Is there a simple way to get the underlying type of a generic collection using reflection? For example, if I have an IList<T>, how do I find out the type of T? The best I have been able to do so far is:

    myProperty.PropertyType.UnderlyingSystemType.ToString() 
     
    That gives me a string like this
    :
    "System.Collections.Generic.IList`1[Fsm.Core.Domain.Category]" 

    I can then parse that string to get the underlying type ('Category' in this case).

    The parsing code is an ugly hack--is there a simpler, more direct way to get the type of class T? Thanks for your help.

    David Veeneman
    Foresight Systems
    Saturday, January 10, 2009 1:58 PM

Answers

  • YOu can use

    myProperty.PropertyType.BaseType.GetGenericArguments[0]
    Ewald - Please remember to mark the replies as answers if they help.
    • Marked as answer by David Veeneman Saturday, January 10, 2009 4:35 PM
    Saturday, January 10, 2009 4:21 PM

All replies

  • YOu can use

    myProperty.PropertyType.BaseType.GetGenericArguments[0]
    Ewald - Please remember to mark the replies as answers if they help.
    • Marked as answer by David Veeneman Saturday, January 10, 2009 4:35 PM
    Saturday, January 10, 2009 4:21 PM
  • Thanks--here is the code I used:

    private static string GetElementTypeName(PropertyInfo property)  
    {  
        Type[] genericArguments = property.PropertyType.GetGenericArguments();  
        return genericArguments[0].Name;  
    }  
     
    Saturday, January 10, 2009 4:45 PM