Why Do I Get a Compile Error Here?

  • Thread starter Thread starter C# Learner
  • Start date Start date
C

C# Learner

My class has a member variable declared as:

string address;

Here is a method of my class:

/// <remarks>
/// This is run in a seperate thread.
/// </remarks>
void DoListen()
{
1: listener = new TcpListener(IPAddress.Parse(address), port);
2: listener.Start();
3: for (;;) {
4: Socket client = listener.AcceptSocket();
5: string address = (client.RemoteEndPoint as IPEndPoint).Address.ToString();
6: Connection connection = new Connection(client);
7: }
}

I get a compile error on line 5:

"A local variable named 'address' cannot be declared in this scope because it would
give a different meaning to 'address', which is already used in a 'parent or
current' scope to denote something else"

Am I missing something, or have I encountered a C# compiler bug?
 
C# Learner said:

Oh, I understand now. The following reproduces it:

void FooBar()
{
address = "foo";
if (true) {
string address = "bar";
}
}

I guess the underscore advocates will have a field day now. :-P
 
In line one you have "address" and in line 5 you are declaring "address" a
second time. You either need to remove "string" from in front of the second
"address" or change the second "address" to another name.

Regards,
John
 
C# Learner said:
[...]
void FooBar()
{
address = "foo";
if (true) {
string address = "bar";
}
}
[...]

Or, even simpler:

void FooBar()
{
address = "foo";
string address = "bar";
}

Also note that it's no longer an error if 'this' is used in the first statement.
 
Back
Top