Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass method parameter when expected to be generic interface base type in c#?

Suppose I have an interface defined as follows:

interface IContract
{
    void CommonMethod();
}

and then another interface which inherits from this interface defined in the manner of:

interface IContract<T> : IContract where T : EventArgs
{
    event EventHandler<T> CommonEvent;
}


My specific question is, given any instance implementing IContract, how could I determine if is also IContract<T>, and if so, what the generic type of IContract<T> is without hard-coding each known type of IContract<T> I might encounter.


Ultimately, I would use this determination in order to make a call of the following pattern:

void PerformAction<T>(IContract<T> contract) where T : EventArgs
{
    ...
}
like image 944
Lemonseed Avatar asked Jan 29 '26 10:01

Lemonseed


1 Answers

As you need an instance of IContract<T> you have to use reflection to get the generic type-param first and than call the appropriate method:

// results in typeof(EventArgs) or any class deriving from them
Type type = myContract.GetType().GetGenericArguments()[0]; 

Now get the generic type-definiton for IContract<T> and get the appropriate method.

// assuming that MyType is the type holding PerformAction
Type t = typeof(MyType).MakeGenericType(type); 
var m = t.GetMethod("PerformAction");

Alternativly if only the method PerforAction is generic instead of MyType:

// assuming that MyType is the type holding PerformAction
Type t = typeof(MyType); 
var m = t.GetMethod("PerformAction").MakeGenericMethod(type);

Now you should be able to invoke the method on an instannce of IContract:

var result = m.Invoke(myInstance, new[] { myContract } );

Where myInstance is of type MyType.

like image 58
MakePeaceGreatAgain Avatar answered Jan 31 '26 00:01

MakePeaceGreatAgain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!