views:

363

answers:

2

Hi,

I'm reflecting a property 'Blah' its Type is ICollection

    public ICollection<string> Blah { get; set; }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        var pi = GetType().GetProperty("Blah");
        MessageBox.Show(pi.PropertyType.ToString());
    }

This gives me (as you'd expect!) ICollection<string> ...

But really I want to get the collection type i.e. ICollection (rather than ICollection<string>) - does anyone know how i'd do this please?

+6  A: 

You're looking for the GetGenericTypeDefinition method:

MessageBox.Show(pi.PropertyType.GetGenericTypeDefinition().ToString());
SLaks
Note that this will return "ICollection`1[T]", which is CLR-speak for "ICollection<T>". I would have suggested the same, so +1.
LukeH
Thanks, that works a treat!
Andy Clarke
+3  A: 

You'll want to look at GetGenericTypeDefinition for example:

   List<String> strings=new List<string>();


        Console.WriteLine(strings.GetType().GetGenericTypeDefinition());
        foreach (var t in strings.GetType().GetGenericArguments())
        {
            Console.WriteLine(t);

        }

This will output:

System.Collections.Generic.List`1[T]
System.String

JoshBerke