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?
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)
public class MyClass
{
public MyClass() : this(0)
{
}
public MyClass(int id)
{
//Same behaviour
}
}
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