17

I got a generic Interface like this :

public interface IResourceDataType<T>
{
    void SetResourceValue(T resValue);
}

Then I got this class that implements my Interface :

public class MyFont : IResourceDataType<System.Drawing.Font>
{
    //Ctor + SetResourceValue + ...
}

And finally I got a :

var MyType = typeof(MyFont);

I, now, want to get the System.Drawing.Font Type from MyType ! At the moment, I got this code :

if (typeof(IResourceDataType).IsAssignableFrom(MyType))
{
    //If test is OK
}

But I don't manage to "extract" my Type here... I tried a couple of things with GetGenericArguments() and other things but they either don't compile or return a null value/List... What do I have to do ?

EDIT : Here is the solution that fit my code for those who will get the same problem :

if (typeof(IResourceDataType).IsAssignableFrom(MyType))
{
    foreach (Type type in MyType.GetInterfaces())
    {
        if (type.IsGenericType)
            Type genericType = type.GetGenericArguments()[0];
        }
    }
}
Guillaume Slashy
  • 3,554
  • 8
  • 43
  • 68
  • Have you seen this post: http://stackoverflow.com/questions/557340/c-sharp-generic-list-t-how-to-get-the-type-of-t – Brad Christie Jan 16 '12 at 14:30
  • Yep, and a couple of another ones, they don't answer to my question... My feeling is that I have to use GetInterfaces() and do some other things, I'm actually trying it ! – Guillaume Slashy Jan 16 '12 at 14:32

2 Answers2

13

Since your MyFont class only implements one interface, you can write:

Type myType = typeof(MyFont).GetInterfaces()[0].GetGenericArguments()[0];

If your class implements several interfaces, you can call the GetInterface() method with the mangled name of the interface you're looking for:

Type myType = typeof(MyFont).GetInterface("IResourceDataType`1")
                            .GetGenericArguments()[0];
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
6
var fontTypeParam = typeof(MyFont).GetInterfaces()
    .Where(i => i.IsGenericType)
    .Where(i => i.GetGenericTypeDefinition() == typeof(IResourceDataType<>))
    .Select(i => i.GetGenericArguments().First())
    .First()
    ;

This takes care of you concern about renaming the interface. There's no string literal, so a rename in Visual Studio should update your search expression.

Jacob Robbins
  • 1,860
  • 14
  • 16