Click here to Skip to main content
15,878,602 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i'm working on a project and I can't seem to figure out why i'm getting this error. here is the full error
A local or parameter named 'waterAmount' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter 


and here is the code

public void WaterMethod()
	{
		int waterAmount;

		Console.WriteLine("In ounces, enter the amount of water that will be put in.");
		waterAmount = int.Parse(Console.ReadLine());

		if (waterAmount => 42)
		{

		}
	}

Thanks in advance for any help

What I have tried:

looking up questions about this error on sites like this
Posted
Updated 7-Mar-20 12:34pm

"=>" defines a lambda expression. You want ">=" which is a comparison operator (greater than or equal to). By making a lambda you're re-defining waterAmount.

EDIT:
For a more detailed explanation of what's going on, a lambda can capture it's enclosing scope's variables. One side effect of this is that symbols (like waterAmount) can not be duplicated between the lambda's scope and enclosing scope. For instance, how would you resolve the following:
C#
int waterAmount;
Func<int, int> lambda = waterAmount => waterAmount * waterAmount;

Which waterAmount does the lambda's code refer to? The parameter twice, the local twice, or a mix?

This also applies to local/nested functions (functions defined in functions).

For more: The Beauty of Closures[^]
 
Share this answer
 
v4
Comments
Patrice T 7-Mar-20 21:29pm    
I din't see this one :) +5
Richard Deeming 9-Mar-20 17:19pm    
Good spot! In this case, the second error message is slightly more helpful than the first:
CS1660 Cannot convert lambda expression to type 'bool' because it is not a delegate type
Jon McKee 9-Mar-20 19:44pm    
Haha, indeed. That is a much more useful error message 👍
Quote:
A local or parameter named 'waterAmount' cannot be declared in this scope because that name is used in an enclosing local scope

Impossible to answer this as you removed the offending part of your code.
Update your question with completed code.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900