-
Consider this snippet:
The second call to To prevent it, I must introduce another variable and capture it instead of
The problem is that it is still a variable, it pollutes the code, and generated implementation of the lambda has a mutable (not a read only) I'd like to be able to instruct compiler to do it automatically, so the value of
It gets even more interesting with complex types:
Here I have a choice what kind of variable to introduce for the capture:
vs
For the latter case compiler could generate:
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 4 replies
-
In the past we've discussed the idea of adding a modifier that would cause closures to capture by value instead of by reference. These are tweaks that exist in other languages like C++. That would provide the semantics that you want in this particular case. The general feeling though was that it's not worth the conceptual trade off to add to the language. |
Beta Was this translation helpful? Give feedback.
-
I think it's related to readonly locals. It's better to use an analyzer (as discussed in that thread and elsewhere) to default to readonly locals, and it'll force you to create another variable to avoid bugs. Yes, it's a little boilerplate, but I think it would be beneficial in other ways, too, to adopt the readonly style of coding. (Disclosure: I haven't made the switch yet, but in my defense I'm pretty busy these days.) |
Beta Was this translation helpful? Give feedback.
-
static void Main(string[] args)
{
var j = 0;
var x = Capture(j);
Console.WriteLine(x());
j = 42;
Console.WriteLine(x());
}
static Func<T> Capture<T>(T arg)
{
return () => arg;
} |
Beta Was this translation helpful? Give feedback.
In the past we've discussed the idea of adding a modifier that would cause closures to capture by value instead of by reference. These are tweaks that exist in other languages like C++. That would provide the semantics that you want in this particular case.
The general feeling though was that it's not worth the conceptual trade off to add to the language.