Joseph Joseph - 1 month ago 8
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
. How can I do this?

I tried using
is object
, and
is System.Object
, but it will not make this distinction. Using
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?


I think you can check runtime like below.


Please check this link for more details.