.Net Tips — How to determine if a type implements a generic interface type

When you have a gener­ic inter­face such as:

public interface IInitializable<T>
    bool IsInitialized { get; }
    void Initialize(T initObject);

It’s easy to check whether a giv­en instance imple­ments the IIni­tial­iz­able inter­face with a spe­cif­ic T:

public class IntInitializable : IInitializable<int>
    public bool IsInitialized { get; private set; }
    public void Initialize(int initObject) { IsInitialized = true; }
var intInit = new IntInitializable();
Console.WriteLine(intInit is IInitializable<int>);  // outputs TRUE

But what if you want to find out if a type imple­ments the IIni­tial­iz­able inter­face of an arbi­trary T? You won’t be able to sim­ply get away with this:

Console.WriteLine(intInit is IInitializable<>);  // doesn't compile

Instead, you can do some­thing like this:

var isIInitializable = 
           .Any(i => i.IsGenericType && 
                     i.GetGenericTypeDefinition() == typeof(IInitializable<>));

And if you want to find out what T is at run­time:

var t = intInit.GetType()
               .First(i => i.IsGenericType && 
                           i.GetGenericTypeDefinition() == typeof(IInitializable<>))

Liked this post? Why not support me on Patreon and help me get rid of the ads!