Keith Devens .com |
Tuesday, December 2, 2008 | ![]() |
| This is not The Greatest Song in the World, oh no. This is just a tribute. – Tenacious D | ||
|
| ← Slashdot | TurboGears: Python on Rails? | Ig Nobel Prizes → |

James Manning (http://blog.sublogic.com/) wrote:
Keith (http://keithdevens.com/) wrote:
Are you saying that C# delegates that are specified inline are closures?
Keith (http://keithdevens.com/) wrote:
Ah, looks like it. Rock! Now to see if I can mutate the data closed by the closure...
Keith (http://keithdevens.com/) wrote:
Yep, I can:
using System;
class Foo {
public int amount;
public Foo(int amount) { this.amount = amount; }
public Predicate<int> isMoreThan() {
return delegate(int i) {
return i > amount++; //inflation
};
}
}
class Program {
static void Main(string[] args) {
Foo f = new Foo(30);
Predicate<int> bar = f.isMoreThan();
Console.WriteLine(bar(31));
Console.WriteLine(f.amount);
Console.WriteLine(bar(31));
}
}
Prints:
True
31
False
Keith (http://keithdevens.com/) wrote:
And another test:
using System;
class Foo {
public Predicate<int> isMoreThan(int amount) {
return delegate(int i) {
return i > amount++; //inflation
};
}
}
class Program {
static void Main(string[] args) {
Foo f = new Foo();
Predicate<int> bar = f.isMoreThan(30);
Console.WriteLine(bar(31));
Console.WriteLine(bar(31));
}
}
Prints:
True
False
Feel free to post a comment below. Please see my comment policy.
Formatting Rules (No HTML):
Generated in about 0.192s.
(Used 8 db queries)

the inline delegates are of the most value in my experience based on the ability to interact with other local variables. Without that, it's more just avoiding the syntax of putting that delegate logic out to its own method, but once you're interacting with local variables, you have far more power at work. Of course, the compiler has more work to do as it needs to create a new type for you, but it's all hidden and, more importantly, done right by the compiler instead of putting that burden on the developer.