Reputation: 12283
How to get generic interface type for an instance ?
Suppose this code:
interface IMyInterface<T>
{
T MyProperty { get; set; }
}
class MyClass : IMyInterface<int>
{
#region IMyInterface<T> Members
public int MyProperty
{
get;
set;
}
#endregion
}
MyClass myClass = new MyClass();
/* returns the interface */
Type[] myinterfaces = myClass.GetType().GetInterfaces();
/* returns null */
Type myinterface = myClass.GetType().GetInterface(typeof(IMyInterface<int>).FullName);
Upvotes: 6
Views: 5082
Reputation: 9456
Try the following code:
public static bool ImplementsInterface(Type type, Type interfaceType)
{
if (type == null || interfaceType == null) return false;
if (!interfaceType.IsInterface)
{
throw new ArgumentException("{0} must be an interface type", nameof(interfaceType));
}
if (interfaceType.IsGenericType)
{
return interfaceType.GenericTypeArguments.Length > 0
? interfaceType.IsAssignableFrom(type)
: type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == interfaceType);
}
return type.GetInterfaces().Any(iType => iType == interfaceType);
}
Upvotes: 0
Reputation: 595
Why you dont use "is" statement? Test this:
class Program
{
static void Main(string[] args)
{
TestClass t = new TestClass();
Console.WriteLine(t is TestGeneric<int>);
Console.WriteLine(t is TestGeneric<double>);
Console.ReadKey();
}
}
interface TestGeneric<T>
{
T myProperty { get; set; }
}
class TestClass : TestGeneric<int>
{
#region TestGeneric<int> Members
public int myProperty
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
#endregion
}
Upvotes: 0
Reputation: 9495
Use Name instead of FullName
Type myinterface = myClass.GetType().GetInterface(typeof(IMyInterface).Name);
Upvotes: 1
Reputation: 23770
In order to get the generic interface you need to use the Name property instead of the FullName property:
MyClass myClass = new MyClass();
Type myinterface = myClass.GetType()
.GetInterface(typeof(IMyInterface<int>).Name);
Assert.That(myinterface, Is.Not.Null);
Upvotes: 5
Reputation: 6694
MyClass myc = new MyClass();
if (myc is MyInterface)
{
// it does
}
or
MyInterface myi = MyClass as IMyInterface;
if (myi != null)
{
//... it does
}
Upvotes: 0