25

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

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

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

anfri
  • 455
  • 1
  • 6
  • 13
  • 1
    Delegates were there before Func and Action and in many ways they serve as backward compatibility devices. However, there are instances when you can't get around but create your delegate. – T.S. Jul 26 '13 at 18:45
  • 1
    Watch this http://www.youtube.com/watch?v=8o0O-vBS8W0 Might be useful. – RahulD Jul 26 '13 at 19:49

2 Answers2

46

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);
Lee
  • 142,018
  • 20
  • 234
  • 287
  • 3
    Yep that's pretty logic. I don't know if that was yuor intention, but you just made me realize that Action and Func don't allow type parameters, either.
    Thanks a lot!
    – anfri Jul 26 '13 at 19:39
  • You have two return types in your delegate. I think you meant: public delegate **bool** TryParse(string s, out T value); I wish I could edit it, but the 6 character rule still applies. – user886079 Aug 06 '14 at 20:23
  • @user886079 - Yes I meant `bool`, thanks. – Lee Aug 06 '14 at 22:12
2

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

Arghya C
  • 9,805
  • 2
  • 47
  • 66