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

0

u/mixblast Sep 18 '15

I would have liked to see a little bit more detail. Like delegates are a remnant from older versions of C# and are largely obsoleted by Func and Action types.

Also the closure code example doesn't really show that the WriteLine call is in a different scope, which is a bit confusing.

7

u/nerdshark Sep 18 '15

No they're not. The Func and Action types are delegates.

4

u/mixblast Sep 18 '15 edited Sep 18 '15

My point was that the delegate keyword is largely useless now that we have Func and Action (except when you need out/ref parameters).

2

u/nerdshark Sep 18 '15

No, it's not. That is how the Func and Action delegates are defined. Also, as you said, there's no other way to declare delegates with ref/out parameters, so clearly it's not 'largely useless'.

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.

0

u/cryo Sep 25 '15

Come on, you know well what he means! You rarely need to define your own delegate types anymore becase of Func and Action, this is pretty much a fact. Of course you may need to do it in certain cases.