Reputation: 132
Say I wanted to make an anonymous getter function that would return the current value of a member variable foo. I might write:
Func<int> myFunction = delegate() { return foo; };
But say I wanted a function that takes the value of foo, binds that value into its closure, and then returns that value every time it's called. I'd write the same thing:
Func<int> myFunction = delegate() { return foo; };
How does the C# compiler tell the difference? Is there any way to be more specific in asking what you want?
Upvotes: 2
Views: 129
Reputation: 2913
"Anonymous functions always use closures" or they close over whatever variables they are referencing. It's possible to properly scope these referenced variables with a factory method so that you're Func<int>
returns the value of foo
at the time the Func<int>
is created. Take the following.
private static Func<int> CreateFooFunc(int scopedFoo)
{
return () => scopedFoo;
//FYI, the line above is more concise version of line below
//return () => { return scopedFoo; };
//which is a more concise version of line below
//return delegate() { return scopedFoo; };
}
or non-statically, depending on use case.
private Func<int> CreateFooFunc()
{
var scopedFoo = foo;
return () => scopedFoo;
}
or better non-static version IMHO (others may disagree)
private Func<int> CreateFooFunc()
{
return CreateFooFunc(foo)
}
You can now do the following and myFunction will contain a function which when evaluated, will return the value of foo
at the time it was created.
Func<int> myFunction = CreateFooFunc(foo);
Keep in mind that if the value of foo
itself was mutable (a POCO for instance) then you would have to copy it or something inside of CreateFooFunc
in order to have the same effect.
Upvotes: 0
Reputation: 50825
Take a look at Eric Lippert's two-part article about this, and specifically modified closure "bugs". He does a better job explaining this than anyone else I've read.
@SLaks is right though about being unable to capture the variable's value.
Upvotes: 2
Reputation: 887245
Anonymous functions always use closures.
There is no way to capture a variable's value only.
If you don't want the function to see changes to the variable, you can make a separate temporary variable and use that in the function,
Upvotes: 4