HerbalMart
HerbalMart

Reputation: 1729

C# delegate Func

I came across a line of code that i can't seem to grasp

Let me explain a little.

What i do understand is that with the following line i am defining a type of delegate with the name "myDelegate". This type can hold a pointer to a function with signature int (int, int)

public delegate int myDelegate(int a, int b);

What i do not get is the following line:

public delegate T Func<T>(T a, T b);

I mean why would i define a type called Func which is already defined in the .NET framework ?

Upvotes: 0

Views: 602

Answers (3)

sgtz
sgtz

Reputation: 9019

the Func syntax is there as a convenience, and often it is better to standardise on what they provide IMHO.

Func and Action are both convenient and easy to remember. By contrast, I find the delegate syntax a little clumsy.

Upvotes: 0

Bas
Bas

Reputation: 27105

The .NET Func<T> is different:

T Func<T>();
T2 Func<T1, T2>(T1 arg);
T3 Func<T1, T2, T3>(T1 arg1, T2 arg2);
.. etc

The delegate definition is not wrong, it's the naming that will get confusing with the .NET version.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503140

Well, it certainly seems like a bad idea to declare your own delegate when one with the same name and number of generic type parameters is available in the framework - but it's not invalid. I suggest that if this is code you own, you rename it appropriately. Note that it's not the same as Func<T> as it's using T for both inputs and the output. You might want to call it BinaryOperator or something similar (although binary operators don't have to have the same operand types, nor does the return value have to be of the same type).

Upvotes: 4

Related Questions