Lambda variable scope
Asked Answered
D

1

8

Example:

myObject.Stub(s => s.MyMethod(null)).IgnoreArguments().Return("bleh");

var s = "s";

A variable "s" is defined in a lambda and another variable "s" as a local variable within the same method. Visual Studio tells me "A conflicting variable is defined below" when I hover over the first "s". Why are these conflicting; the "s" in the lambda is not available outside of its enclosing brackets surely?

Dorty answered 28/6, 2010 at 15:20 Comment(1)
See: blogs.msdn.com/b/ericlippert/archive/2009/11/02/…Alagoas
T
9

They are conflicting because a rule of C# is that any two uses of the same simple name cannot be used to refer to two different things inside the block immediately enclosing either of them. In your example the simple name "s" is used to mean two things inside the block enclosing the local variable declaration: it means a local variable, and a lambda parameter. That is what is illegal. I note that the error message you get tells you this:

A local variable named 's' cannot be declared in this scope because it
would give a different meaning to 's', which is already used in a 
'child' scope to denote something else

C# does not allow you to have the same simple name mean two things in the same block because doing so makes code error prone, hard to edit, hard to read, hard to refactor, and hard to debug. It is better to disallow this bad programming practice than to allow it and risk you causing bugs because you assumed that "s" means the same thing throughout the block.

When the code is only two lines long it is easy to remember that there are two different meanings for s, but when it is hundreds of lines long, not so easy.

For more information about this rule, see:

Link

Tonkin answered 28/6, 2010 at 16:40 Comment(1)
hmm, I remembered something about your posting. Thanks for correcting me.Launcelot

© 2022 - 2024 — McMap. All rights reserved.