Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I call constructor from another constructor (as a regular method)?

Tags:

c#

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?

like image 202
Richard77 Avatar asked Mar 11 '26 17:03

Richard77


2 Answers

You can do this:

public class MyClass {
    public MyClass() : this(0) {
    }
    public MyClass(int id) {
    }
}

Here's Microsoft's documentation on it. (you have to scroll down a bit; try searching for : this)

like image 101
icktoofay Avatar answered Mar 13 '26 08:03

icktoofay


public class MyClass
{
   public MyClass() : this(0)
   {
   }
   public MyClass(int id)
   {
     //Same behaviour
   }
}
like image 38
zerkms Avatar answered Mar 13 '26 09:03

zerkms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!