Roy
Roy

Reputation: 2323

How to check whether a type parameter is actually an interface

I have a generic function and I want to check whether the type parameter is an interface. Is there anyway to do that? Thanks in advance!

Upvotes: 4

Views: 222

Answers (3)

Rich
Rich

Reputation: 3101

If you want to constrain your generic method so that the type parameter can only be a type that implements some specific interface and nothing else, then you should do the following:

void YourGenericMethod<T>() where T : IYourInterface {
    // Do stuff. T is IYourInterface.
}

Upvotes: 5

Igor Zevaka
Igor Zevaka

Reputation: 76500

You can explicitly check the generic type parameter using typeof operator and Type.IsInterface property.

void MyMethod<T>() {
  bool isInterface = typeof(T).IsInterface;
}

Upvotes: 4

Quintin Robinson
Quintin Robinson

Reputation: 82335

Use the IsInterface property of Type..

public void DoCoolStuff<T>()
{
    if(typeof(T).IsInterface)
    {
        //TODO: Cool stuff...
    }
}

Upvotes: 9

Related Questions