Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are these examples C# closures?

Tags:

closures

c#

I still don't quite understand what a closure is so I posted these two examples and I want to know whether these examples are both closures or not?

Example A:

List<DirectoryInfo> subFolders = new List<DirectoryInfo>();

Action<string> FilterSubFoldersStartA =
  s => subFolders.
       AddRange((new DirectoryInfo(s)).GetDirectories().
       Where(d => d.Name.StartsWith("A")));

FilterSubFoldersStartA(@"c:\tempa");
FilterSubFoldersStartA(@"c:\tempb");

Example B:

List<DirectoryInfo> subFolders = new List<DirectoryInfo>();

string filter = "A";

Action<string> FilterSubFoldersStartGen =
  s => subFolders.
       AddRange((new DirectoryInfo(s)).GetDirectories().
       Where(d => d.Name.StartsWith(filter)));

FilterSubFoldersStartGen(@"c:\tempa");

filter = "B"; 

FilterSubFoldersStartGen(@"c:\tempb");
like image 425
tuinstoel Avatar asked Oct 23 '09 08:10

tuinstoel


1 Answers

Your second example makes use of closures (technically you could say that the compiler computes a closure in both cases, but you don't make use of it in the first case).

A closure is simply "all the variables visible to this function". Nothing more, nothing less. And obviously, in both cases, those variables exist, and are determined by the compiler.

But what we usually mean when we talk about "using closures" is that lambda expressions can use all local variables visible at the place they're declared. They're all part of its closure.

In your case, d is simply the parameter to the lambda function, and since that's all you use in the first case, you're not really taking advantage of closures.

In the second case, filter is not defined in the lambda expression, it's not a parameter or anything. It's a local variable which just so happens to be visible at the place where the lambda is declared. So it is part of the lambda's closure, which allows you to reference it in the body of the lambda.

Edit
As pointed out in the comments, I didn't read your code too closely. I only noticed the second lambda expression in each example. The first lambda does use closures (it closes over subFolders in both cases.)

like image 175
jalf Avatar answered Sep 20 '22 23:09

jalf