views:

53

answers:

1

In c#,I am using the following code:

IPAddress localaddress=IPAddress.Parse("127.0.0.1");

to get a System.Net.IPAddress instance which am using in:

IPEndPoint ip= new IPEndPoint(localaddress,5555);

I am however getting an error saying:

A field initializer cannot reference the nonstatic field, method, or property 'WindowsApplication1.lanmessenger.localaddress'   .

Please help.

+1  A: 

I'm guessing your code looks like this:

public class lanmessenger {
  IPAddress localaddress=IPAddress.Parse("127.0.0.1");
  IPEndPoint ip= new IPEndPoint(localaddress,5555);

  public lanmessenger(){
  ...
  }
}

The problem here is that the compiler doesn't want you using initialized fields the way you are. You're using localaddress to initialize ip, which is problematic from the compiler's prospective. Two ways to get around this:

Inline it:

 IPEndPoint ip= new IPEndPoint(IPAddress.Parse("127.0.0.1");,5555);

Or just do it in the constructor: (generally better)

public class lanmessenger {
  IPAddress localaddress;
  IPEndPoint ip;

  public lanmessenger(){
    this.localaddress = IPAddress.Parse("127.0.0.1")
    this.ip = new IPEndPoint(localaddress,5555);
  }
}
Patrick
yeah i inferred that..Used the first alternative and its working.Thanks a lot.
Avik
No problem, man. :)
Patrick