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?
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 (orObject
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.
: this(...)
construct specifies another constructor in the same class to be the initiliser for the constructor that it is applied to.: 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.