tags:

views:

80

answers:

4

C# in VS2005: if a class has two constructors, what is the best way for these constructors to share some code?

eg. How could I avoid having the x = 5 and y = 10 lines in both constructors for the following:

public class MyObject {

int x;
int y;
int z;

public MyObject() {
    x = 5;
    y = 10;
}

public MyObject(int setZ) {
    x = 5;
    y = 10;
    z = setZ;
}
+3  A: 

Use the this() syntax.

public MyObject(int setZ) : this() {
    z = setZ;
}
Matthew Flaschen
@Matthew: what if the class is inherited? Will this() call the base constructor as well?
Craig Johnston
`MyObject()` calls the base parameterless constructor implicitly.
Matthew Flaschen
@Craig, `base()` will be implicitly called if you do not do so directly. The base class will be constructed before the derived class no matter which derived constructor is called.
Anthony Pegram
+9  A: 

Just chain to the common constructor...

public MyObject(int setZ)
  : this()
{
  z = setZ;
}
Rob
Will this cause the base constructor to be executed if the class is inherited?
Craig Johnston
A: 

Create another method:

private setDefaultNumbers() {
    x = 5;
    y = 10;
}

Then have both versions of your constructor call this method:

public MyObject() {
    setDefaultNumbers();
}

public MyObject(int setZ) {
    setDefaultNumbers();
    z = setZ;
}
Alex Miller
I would only recommend this if setDefaultNumbers is something you could see calling after the object is created. Even if it is private, there is no way to mark it as 'for constructors only' unless it is in the constructors only. If you can I would prefer the chained constructors, unless there is no way to cleanly chain them.
Dolphin
A: 

It's very similar to the way you'd do it with methods. Normally you would do something like:

public void SetA(int a)
{
    this.a = a;
}

public void SetAandB(int a, int b)
{
    this.SetA(a);
    this.b = b;
}

with constructors, there's special syntax for it:

public void MyObject()
{
    this.a = 5;
}

public void MyObject(int b)
    : this()
{
    this.b = 10;
}
SnOrfus