Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegates vs Action, Func in C# [duplicate]

Tags:

c#

delegates

This might seem a silly question, but it's just for curiosity's sake.

We have two particular already-defined delegates in C#:

  • Action<T>
  • Func<T, TResult>

Action encapsulates any "void" method that takes 0 or more parameters.
Func encapsulates any method that returns a specific value type and takes 0 or more parameters.

My question is: in which cases it is recommended to define a custom delegate?
Why would you need to do that?

Thanks in advance

like image 685
anfri Avatar asked Jul 26 '13 18:07

anfri


2 Answers

None of the Func or Action types allow out or ref parameters, so you'll have to define your own delegates if you need to use those e.g.:

public delegate bool TryParse<T>(string s, out T value);
like image 81
Lee Avatar answered Nov 13 '22 07:11

Lee


In thousand cases you'll need to refer/point to a function (hence a delegate, if actual implementation of the function will vary at run time, except the signature) that doesn't match either of the given delegates. Say

Public delegate T MyDel(T t, U u, V v);

like image 41
Arghya C Avatar answered Nov 13 '22 07:11

Arghya C