Reputation: 2137
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.
Upvotes: 0
Views: 201
Reputation: 92520
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);
}
}
Upvotes: 1