0

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 ?

3 Answers 3

4

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).

Sign up to request clarification or add additional context in comments.

6 Comments

Additionally, since the OP said they "came across this code", I guess it's possible it was written before System.Func<T> was introduced in .Net 3.5.
@Sven: True. I always forget which Action and Func overloads were present in .NET 2. Was it just Action<T>?
Action<T> was in .Net 2.0; Action (non-generic) and Func<T> (and its generic overloads) were not.
probably someone was trying "to extend" the generic delegates available in the Framework.I know it is not a good idea but that is what is loos like to me
If i replace Func with [var] which is also a reserved word it also works But if i replace Func with [int] or [while] it does not work. Can you also explain this please ?
|
0

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.

Comments

0

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.

2 Comments

Func isn't "syntax" - it's just a family of framework-provided delegates. When you say you "find the delegate syntax a little clumsy" - do you mean the syntax for declaring a new delegate type?
yes that is what I mean. Just that I prefer seeing them expressed in this way. No it's not C# syntax, but you can incorporate the provided delegates into your style. Your distinction is a useful one though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.