Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there anonymous, type-safe, generic delegate signatures in C# 2.0?

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); }
like image 225
EfForEffort Avatar asked Oct 09 '08 16:10

EfForEffort


People also ask

Can delegates be used with generic types?

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.

What are the three types of generic delegates in C#?

Func, Action and Predicate are generic inbuilt delegates present in System namespace. All three can be used with method, anonymous method and lambda expression.

Which type of delegate will you choose if you want to declare a method that accepts an integer as a parameter and returns an integer?

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.

Which delegate is used for invoking only one method?

The second call of the delegate invokes only one method. delegate void MyDelegate(int x, int y); Our delegate takes two parameters.


1 Answers

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.

like image 161
Jon Skeet Avatar answered Oct 05 '22 05:10

Jon Skeet