How to simplify multiple constructors?

15.6k views Asked by At

I would like to have two constructors for a class, as follows:

public MyClass()
{
    // do stuff here
}

public MyClass(int num)
{
    MyClass();
    // do other stuff here
}

Is the above the correct way to achieve my purpose? Is there some kind of shorthand which is better?

5

There are 5 answers

0
Andrew Cooper On BEST ANSWER
public MyClass()
{
    // do stuff
}

public MyClass(int num)
    : this ()
{
    // do other stuff with num
}

The : this() bit is called a Constructor Initialiser. Every constructor in C# has a an initialiser which runs before the body of the constructor itself. By default the initialiser is the parameterless constructor of the base class (or Object if the class is not explicitly derived from another class). This ensures that the members of a base class get initilised correctly before the rest of the derived class is constructed.

The default constructor initialiser for each constructor can be overridden in two ways.

  1. The : this(...) construct specifies another constructor in the same class to be the initiliser for the constructor that it is applied to.
  2. The : base(...) construct specifies a constructor in the base class (usually not the parameterless constructor, as this is the default anyway).

For more details than you probably want see the C# 4.0 language specification section 10.11.

2
manojlds On

You can do it like this:

public MyClass()
{
    // do stuff here
}

public MyClass(int num) : this()
{

    // do other stuff here
}
0
McGarnagle On

Maybe use one constructor with a default value for the parameter:

public MyClass(int num = 0)
{
    MyClass();
    // do other stuff here
}
1
Daniel Hilgarth On

The correct syntax looks like this:

public MyClass() 
{ 
    // do stuff here 
} 

public MyClass(int num) : this()
{ 
    // do other stuff here 
} 

Note the this() at the second constructor. This calls the constructor in the same class with no parameters.

You could also have it the other way around:

public MyClass() : this(someReasonableDefaultValueForNum)
{ 
} 

public MyClass(int num)
{ 
    // do all stuff here 
} 

There is only one more "function" you can use instead of this at this place which is base:

public MyClass(int num) : base(someParameterOnTheBaseClassConstructor)
{
}

This is useful if you don't want to call the default parameterless constructor in the base class but one of the constructors that takes parameters.

0
Tomtom On

You can do the following:

public MyClass()
   : this(1) { }

public MyClass(int num)
{
   //do stuff here
}