What is the easier way to know if a type param implements an interface in c# 2.0?
-
01-07-2019 - |
Question
For example, given a type param method i'm looking for something like the part in bold
void MyMethod< T >() {
if ( typeof(T).Implements( IMyInterface ) ) {//Do something
else
//Do something else
}
Anwers using C# 3.0 are also welcome, but first drop the .NET 2.0 ones please ;)
Solution
if(typeof(IMyInterface).IsAssignableFrom(typeof(T)))
{
// something
}
else
{
// something else
}
OTHER TIPS
I think
if (typeof (IMyInterFace).IsAssignableFrom(typeof(T))
should also work: but i don't see an advantage...
Ï've just tried using
if( typeof(T).Equals(typeof(IMyInterface) )
...
And also works, but your answer seems more robust and was what I was looking for. Thanks!
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow