2

When should we use Action<T> and not to define a delegate explicitly?

TylerH
  • 20,799
  • 66
  • 75
  • 101
amit kohan
  • 1,612
  • 2
  • 25
  • 47
  • 1
    Dupe: [creating-delegates-manually-vs-using-action-func-delegates](http://stackoverflow.com/questions/4482613/creating-delegates-manually-vs-using-action-func-delegates) – nawfal Jul 07 '14 at 16:48

2 Answers2

2

Well...

Action<T> is almost the same as delegate void (T t)
and
Func<T> is almost the same as delegate T ()

Action and Func (and lambdas) are just 'syntactical sugar' and a convenience for using delegates.

So it's really just a matter of preference.

Randy Minder
  • 47,200
  • 49
  • 204
  • 358
  • @amitkohan Yes, _almost_ the same. One thing to be aware of is contravariance of `Action`. If contravariance is not desired, write your own delegate type without contravariance. See my comment to Servy's answer. – Jeppe Stig Nielsen Nov 12 '12 at 12:02
2

It's entirely a matter of preference, but I see no reason to ever define your own delegate if one of the overloads of Action or Func will work. If you have a ref/out/params parameter, optional arguments, or some other such edge cases you have no choice but to define your own.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • Something else: Since .NET 4.0, `Action` is **contravariant** in `T`. But at the same time, delegate combination ("addition" of two delegate objects) doesn't work with contravariance (Lippert's words: [all messed up](http://stackoverflow.com/a/2307942/1336654)). So suppose you make a `public event Action ItHappened;`. Then because of contravariance, one subscriber could add an `Action` to `ItHappened`, another one an `Action`, a third one `Action`. That throws at runtime! So a reason to use a user-defined type is to **not** have contravariance. – Jeppe Stig Nielsen Nov 12 '12 at 12:00
  • While with Action/Func life is much easier, custom delegates give you better type safety (correctness). In the end there's a trade-off. Another benefit is the better (more meaningful) parameter name and IDE's documentation support. – nawfal Jul 07 '14 at 16:53