Let’s say I have 2 constructors.
public class MyClass
{
public MyClass()
{
int id = 0;
//Same behaviour
}
Public MyClass(int id)
{
//Same behaviour
}
}
Both constructions implement the same behavior. The only difference is that, if the first constructor is called and the value of id = 0;
My question is to know if I can call the second constructor, instead of implemetanting the same behavior? If that’s possible, do I do it?
Yes, this is called constructor chaining. It’s achieved like so:
Note that you can chain to the base-class constructor like so:
If there is a base class and you don’t specify a constructor to chain to, the default is the accessible parameterless constructor, if there is one. If you do not specify a constructor to chain to and there is no accessible parameterless constructor, you will get a compile-time error.