Joseph Joseph - 16 days ago 4
C# Question

In C#, how can I tell whether a generic type, T, is (not implements!) an interface?

Edit: I made a mistake an the premise was wrong. typeof(T).IsClass does indeed work - as does typeof(T)IsInterface, as was pointed out.

Say I have this method:

public T GetService<T>() where T : IService


I want to test whether the generic type, T, was sent into this method as an interface, rather than as a class. In other words, I want to differentiate between a call from
MyClass.GetService<IService>()
and
MyClass.GetService<ImplementingClass>()
. How can I do this?

I tried using
is object
, and
is System.Object
, but it will not make this distinction. Using
typeof(T).IsClass
and
default(T).IsClass
also don't work, because, respectively, the the System.Type return type is always a class, and because IsClass isn't available to a default T.

How else can I do this?

Answer

I think you can check runtime like below.

typeof(T).IsInterface

Please check this link for more details.