c# – What is the difference between Func <> and delegate?

Question:

Both are used to return a value, and both can take multiple parameters.
What is the difference between them?

Answer:

Well, there is the delegate keyword – this is a description of the signature of the function, that is, its parameter list and the type of the return value. Used like this:

public delegate bool MyPredicate(int x);

You can use it like this:

private bool IsOdd(int i) { return i % 2 != 0; }

private Analyze(MyPredicate p, int x)
{
    bool result = p(x);
    if (result)
        Console.WriteLine("found!");
}

Analyze(IsOdd, 1); // печатает "found!"

On the other hand, there are ready-made, predefined function signatures ( Func<TArg1, TArg2, ..., TResult> with a return value, Action<TArg1, Targ2, ...> without). That is, you can not define the delegate yourself, but use ready-made Func and Action . A similar example:

private bool IsOdd(int i) { return i % 2 != 0; }

private Analyze(Func<int, bool> p, int x)
{
    bool result = p(x);
    if (result)
        Console.WriteLine("found!");
}

Analyze(IsOdd, 1); // печатает "found!"

If Func or Action is appropriate for your signature, there isn't much point in defining your delegate. Or there is if you want to give your delegate a better name than just Func and want to emphasize its semantics .

There are cases when you still need to declare your delegate. For example, the presence of out and ref parameters:

public delegate Updater(ref int x); // невозможно выразить через Func

For completeness, here's a (hopefully complete) list of when you need to declare a delegate:

  • When the argument list is too long (for .NET 4+ more than 16 arguments, for .NET 3.5 more than 4 arguments)
  • When your arguments contain ref , out or params .
  • If your delegate is recursive (e.g. delegate DD(D d) ). Oddly enough, such things are sometimes needed .
  • If you want to give meaningful names to your delegate arguments ( Action / Func arguments are named arg1 , arg2 , etc.).
Scroll to Top