1

I have the following code:

int i = 5;
Func<int> getValue = () => i + 1;

The C# compiler add a closure to automatically transform the variable i into a field, and then uses inside the delegate. I want to avoid this in my entire solution. Possibly getting a compiler error, like: "Variable 'i' is not declared."... Is this possible? Maybe a Rosyln Compiler validator?

  • How would you like to write the delegate instead? If it needs access to `i` you're going to have provide it some way. – Sean Apr 17 '20 at 12:59
  • 3
    This is how [closures](https://stackoverflow.com/questions/428617/what-are-closures-in-net) work. You can't opt-out as far as I am aware. – Wiktor Zychla Apr 17 '20 at 12:59
  • @Sean I want to force something like this: int i = 5; Func getValue = j => j + 1; – Everton Elvio Koser Apr 17 '20 at 13:00
  • @WiktorZychla Ty, I will edit my question! – Everton Elvio Koser Apr 17 '20 at 13:01
  • They're 2 different things. If you don't want a closure over a variable then just don't write it that way in the first place! – Sean Apr 17 '20 at 13:01
  • 1
    This seems like the kind of thing you'd look for if you accidentally capture a few times. The right fix for that is usually gain more experience, not to seek to neuter the language. – Damien_The_Unbeliever Apr 17 '20 at 13:02
  • You could write a Roslyn plugin to detect variable capture in the lambda, but why are you so worried about it in the first place? – Sean Apr 17 '20 at 13:03
  • @Sean Because the entire project is a legacy from C# 2.0 and have millions os lines and it was proposed to not have this functionality. Now, when it happens, It results in error very hard to identify. Like now: We cloned the original object in memory to have an state if the operation was invalid. But, because of the closure, some of the operations are made on the backup and saving to the database... – Everton Elvio Koser Apr 17 '20 at 13:12
  • 1
    *"project is a legacy from C# 2.0 and have millions os lines"* - then don't use lambdas. – Sinatr Apr 17 '20 at 13:17
  • @Sinatr very helpful comment, indeed. – Everton Elvio Koser Apr 17 '20 at 13:19
  • One of possible approaches is to refactor your code so you don't have inline functions assigned to delegates. Each such delegate should be made into an external function. Each variable that was previously caught under a closure is now an undeclared identifier. – Wiktor Zychla Apr 17 '20 at 17:32

0 Answers0