Why am I getting a stack overflow when using properties in the constructor?
I have a non-static class in which i have several properties, ie serverURL, serverPort etc, and the class has a constructor. The constructor accepts arguments which it then uses to 'set' the properties, initialising them. Here is the code:
public Server(string newServerAddress, int newServerPort) {
serverAddress = newServerAddress;
serverPort = newServerPort;
}
public string serverAddress {
get {
return serverAddress;
}
set {
serverAddress = value;
}
}
public int serverPort {
get {
return serverPort;
}
set {
serverPort = value;
}
For some reason this gives me a stack overflow error, and I have no idea why. Here is the code being used to cal开发者_StackOverflowl it:
Server test = new Server("server.url.here",8080);
This code is obviously bound by a class, but I left it out here. This is an amateur problem, and I've done things like this before but I'm completely bewildered by what is going on, and when I try and debug it in visual studio, it tells me that it can't debug it, presumably since it's using the stack to debug.
Observe the case-sensitivity. The property is returning itself.
public string serverAddress {
get {
return serverAddress; // recursing here
}
}
You forgot to use a backing field for the properties. The property setter uses the property itself, recursing endlessly. Fix it like this:
private string mServerAddress;
public string serverAddress {
get {
return mServerAddress;
}
set {
mServerAddress = value;
}
}
Or use the automatic property syntax:
public string ServerAddress { get; set; }
You have the recursion in property setter or getter. Try this code instead:
public Server(string newServerAddress, int newServerPort) {
serverAddress = newServerAddress;
serverPort = newServerPort;
}
public string serverAddress { get; set; }
public int serverPort { get; set; }
You are referencing the setter within the setter...
within your property serverAddress, you have the line:
serverAddress = value
which is going to go to the setter for the serverAddress property, and loop inifintely...
use the following syntax:
private string _serverPort;
public string ServerPort
{
get { return _serverPort; }
set { _serverPort = value; }
}
Hope this helps :)
精彩评论