Consider the delegate for a generic A
to B
function:
public delegate B Fun<A, B>(A x);
I can then write a function that accepts and invokes the Fun
delegate:
public static B invokeFun<A, B>(A x, Fun<A, B> f)
{ return f(x); }
(Never mind whether it is wise to write invokeFun
.)
Can I write invokeFun
without naming the Fun
delegate? I would expect something like this to work, but it doesn't:
public static B invokeFun<A, B>(A x, B (A) f)
{ return f(x); }
Delegates defined within a generic class can use the generic class type parameters in the same way that class methods do. Generic delegates are especially useful in defining events based on the typical design pattern because the sender argument can be strongly typed and no longer has to be cast to and from Object.
Func, Action and Predicate are generic inbuilt delegates present in System namespace. All three can be used with method, anonymous method and lambda expression.
C# Example of Delegate type Definition The myDelegate is a user-defined name of the delegate that takes a single integer parameter and returns an integer value. Therefore, the myDelegate references and invokes a method that takes a single integer parameter and returns an integer value.
The second call of the delegate invokes only one method. delegate void MyDelegate(int x, int y); Our delegate takes two parameters.
No, there aren't.
The closest you can get is the two generic delegate families in .NET 3.5: Func
and Action
. Obviously they're not actually present in .NET 2.0 (except Action<T>
), but they're trivial to write - and indeed I've done so for you :)
Personally I'm glad the "uber-short" syntax is invalid - I find it harder to understand than the normal "here's the type, here's the name" syntax for the parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With