views:

63

answers:

4

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 call 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.

+4  A: 

Observe the case-sensitivity. The property is returning itself.

public string serverAddress {
    get {
        return serverAddress; // recursing here
    }
}
Andrew Keith
Ah, thanks. They're more like a public interface than a field then, which confused me.
George
+1  A: 

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; }
Dmytrii Nagirniak
+3  A: 

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; }
Hans Passant
+1  A: 

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 :)

IanR