I have an object that I want to call certain methods if it implements specific kinds of interfaces.
I am checking for the generic interfaces like below.
foreach (var iFace in objectType.GetInterfaces())
{
if (iFace.IsGenericType && iFace.GetGenericTypeDefinition() == typeof(INotify<>))
{
//fails to compile because object isn't the correct type.
doSomethingWithINotifyObject(notifyObject)
}
//do other things if different interfaces
}
What I don't know how to do is cast the object so that it is the correct type to call doSomethingWithINotifyObject
The method in this example looks something like this
private void doSomethingWithINotifyObject<T>(INotify<T> notify) where T : EventArgs, INotificationArgs
{
//do stuff with notification object
}
The INotify interface is defined as
public interface INotify<T> where T: EventArgs, INotificationArgs
{
//notify stuff
}
Is there any way to cast my object to an INotify<T> where T : EventArgs, INotificationArgs
and not care what T actually is?
I tried making a generic method like the following
typeof(MyClass)
.GetMethod("doSomethingWithINotifyObject")
.MakeGenericMethod(notifyObject.GetType())
.Invoke(this, new object[] { notifyObject });
And I get the following runtime exception
Run-time exception (line 13): GenericArguments[0], 'MyClass+doSomethingWithINotifyObject', on 'Void doSomethingWithINotifyObjectT' violates the constraint of type 'T'.
Stack Trace:
[System.Security.VerificationException: Method MyClass.doSomethingWithINotifyObject: type argument 'MyClass+doSomethingWithINotifyObject' violates the constraint of type parameter 'T'.] at System.RuntimeMethodHandle.GetStubIfNeeded(RuntimeMethodHandleInternal method, RuntimeType declaringType, RuntimeType[] methodInstantiation) at System.Reflection.RuntimeMethodInfo.MakeGenericMethod(Type[] methodInstantiation)
[System.ArgumentException: GenericArguments[0], 'MyClass+doSomethingWithINotifyObject', on 'Void doSomethingWithINotifyObjectT' violates the constraint of type 'T'.] at System.RuntimeType.ValidateGenericArguments(MemberInfo definition, RuntimeType[] genericArguments, Exception e) at System.Reflection.RuntimeMethodInfo.MakeGenericMethod(Type[] methodInstantiation) at MyClass.Main() :line 13
I have an example of this scenario on .NET fiddle here https://dotnetfiddle.net/ZWMJ4x