C#: if a class has two constructors, what is the best way for these constructors to share some code? [duplicate]
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;
}
Just chain to the common constructor...
public MyObject(int setZ)
: this()
{
z = setZ;
}
Use the this()
syntax.
public MyObject(int setZ) : this() {
z = setZ;
}
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;
}
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;
}
精彩评论