I have the following code (generates a quadratic function given the a, b, and c)
Func<double, double, double, Func<double, double>> funcGenerator = (a, b, c) => f => f * f * a + b * f + c;
Up until now, lovely.
But then, if i try to declare a variable named a, b, c or f, visual studio pops a "A local variable named 'f' could not be declared at this scope because it would give a different meaning to 'f' which is used in a child scope."
Basically, this fails, and I have no idea why, because a child scope doesn’t even make any sense.
Func<double, double, double, Func<double, double>> funcGenerator =
(a, b, c) => f => f * f * a + b * f + c;
var f = 3; // Fails
var d = 3; // Fine
What’s going on here?
I think what you’re misunderstanding is that the order of declarations does not matter to the C# compiler with respect to scoping rules.
This:
Is exactly the same as this:
Scopes aren’t order-sensitive. You have a local variable named
f, and you are trying to declare another variable namedfinside the lambda. This is illegal according to the C# spec.Specifically, it would conflict with the ability of lambdas to do variable capturing. For example, this code is legal:
This is completely legal and executing
func()will return4. That’s why you can’t declare another variablexhere inside the lambda – because the lambda actually needs to be capable of capturing the outerx.Just change the name of one of the
fvariables.