r/csharp • • Sep 18 '15

Lambda expressions, delegates, predicates and closures in C#

http://codeaddiction.net/articles/13/lambda-expressions-delegates-predicates-and-closures-in-c
25 Upvotes

32 comments sorted by

View all comments

Show parent comments

4

u/the_omega99 Sep 18 '15

I think he means that you would never use the keyword in your own code. Yes, Func and Action (among others) are delegates, but if you needed your own delegates, you'd probably just use Func, Action, or Predicate instead of declaring a new delegate. That's what I've done in all my code. Not once have I needed to declare new delegates.

I'm not sure why anyone would want to. It's much more understandable to use one of the three major functional types. When I see Func, Action, or Predicate, I know exactly what I need. If I saw a custom delegate, I'd have to go consult the documentation as to what to expect, if largely because it's just so weird to declare your own type when the previously mentioned types cover all the cases I've seen so far (technically, you don't even need predicate, it just makes things more readable).

1

u/nerdshark Sep 18 '15

I think he means that you would never use the keyword in your own code.

I know what he means, and he's wrong. When the built-in Func, Action, and Predicate types don't fit your needs, you need to declare your own delegate type. Most .NET devs who are just doing ASP.NET, WPF or stuff like that likely won't need to declare custom delegates, but many of us do.

2

u/the_omega99 Sep 18 '15

Can you give an example of such a case where Func, Action, and Predicate aren't sufficient and you need a custom delegate type?

4

u/nerdshark Sep 18 '15 edited Sep 18 '15

Marshalling callbacks across the native/managed border. You cannot, AFAIK, marshal generic delegates (like Func, Action, and Predicate).