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?
A class can have multiple constructors that assign the fields in different ways. Sometimes it's beneficial to specify every aspect of an object's data by assigning parameters to the fields, but other times it might be appropriate to define only one or a few.
Prerequisite: Constructors in C# A user can implement constructor overloading by defining two or more constructors in a class sharing the same name. C# can distinguish the constructors with different signatures. i.e. the constructor must have the same name but with different parameters list.
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.
: 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With