Hacker News new | past | comments | ask | show | jobs | submit login
C# Closures Explained (codethinked.com)
48 points by fogus on June 23, 2010 | hide | past | favorite | 6 comments



Javascript (with Prototype and later jQuery) taught me how to do functional programming. Or at least made me love it. I actually began to prefer programming JavaScript for the power/freedom. Glad to see I can do about the same thing now in C# with the var keyword and closures, first class functions, etc.


Python did the same for me. Closures was not a new feature as of C# 3.0. It is a part of C# 2.0. The problem is that the syntax is so verbose and horrible in 2.0 that the readability of the code can be quite messy and almost not worth the effort.

C# 3.0 greatly simplified things with the introduction of the lambda function syntax hence why a lot more people have suddenly "discovered" closures in .NET.

When first learning C# 2.0 I had a lot of difficulty understanding how to use delegates with closures mainly because I couldn't get past the syntax. Learning and using Python shortly after helped me tremendously in understanding how closures worked and when to use them because (not surprisingly) the Python syntax is so much cleaner and intuitive. I was able to then transfer and apply this knowledge to C# by cutting through the noise and using closures effortlessly (as needed). When lambdas arrived in 3.0, it was a no brainer.

This experience showed me how being exposed to and learning other programming languages that follow different paradigms can have a positive impact on how you write code in your primary language.


Something I sorely missed when I still worked for the man.

Anyhow, in Lisp, visually, a LET with it's enclosing parens makes it much faster to see the closed-over variables.


Don't you mean 'lambda'?


I think I meant what I said :-), which is that closing over a lexical variable in Lisp, using LET, more clearly, to my eyes at least, show which variables are hidden/closed over.

For example, in CL, this guy's example would take the general form:

(let ((counter 0))

   (defun tally () 

      (incf counter)))

So, in this form, I know that TALLY hides/closes over COUNTER, without needing to inspect the function body (either before, or within a λ that might be returned from within the function body).


Useful. I'd heard the term closure bandied around, but never bothered to learn what it was. Cheers.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: