Constructor Parameters in C#

I might be the only person coding in C# on a regular basis who doesn’t know this, but constructors can have a : this(param1, param2,…) as well as a : base… This means no more creating a private Init method that all the constructors call.

This is what I used to do:


public class Server
{
private int m_port;
private IPAddress m_address;

public Server()
{
Init(IPAddress.Any, 8181);
}

public Server(int port)
{
Init(IPAddress.Any, port);
}

public Server(IPAddress address, int port)
{
Init(address, port);
}

private void Init(IPAddress address, int port)
{
m_port = port;
m_address = address;
}
}

But this is what I can do now:


public class Server
{
private int m_port;
private IPAddress m_address;

public Server()
: this(8181) { }

public Server(int port)
: this(IPAddress.Any, port) { }

public Server(IPAddress address, int port)
{
m_port = port;
m_address = address;
}
}
This entry was posted in Mike and tagged .