Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the constraint 'delegate'

Tags:

c#

C# now allows delegate constraints in generics. As I was trying to learn the new feature, I could not come with a single practical way of using it. As others have been asking for this feature for years, I am obviously missing the point here.

public class Test<TDelegate> where TDelegate : Delegate
{
    readonly TDelegate fd; // no way to call this 
    public event TD Evt; // not even legal
}

How does a class do anything useful with a generic parameter that is a delegate?


1 Answers

All you have to do is:

public static void Foo<T>(T t) where T : System.Delegate
{
    t.DynamicInvoke();
}

For some reason, the normal Invoke() isn't a valid method that can be used.

like image 152
AustinWBryan Avatar answered Oct 24 '25 00:10

AustinWBryan



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!