Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a type parameter is actually an interface

Tags:

c#

.net

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!

like image 528
Roy Avatar asked Dec 02 '22 04:12

Roy


2 Answers

Use the IsInterface property of Type..

public void DoCoolStuff<T>()
{
    if(typeof(T).IsInterface)
    {
        //TODO: Cool stuff...
    }
}
like image 171
Quintin Robinson Avatar answered Jan 14 '23 17:01

Quintin Robinson


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.
}
like image 23
Rich Avatar answered Jan 14 '23 19:01

Rich