C
C#•3d ago
yourFriend

Silly OOP question about constructors

I am learning OOP and came across this. A way to reuse constructors:
public Dog() : this("NoName") {}

public Dog(string name) : this(name, 1) {}

public Dog(string name, int age) : this(name, age, 0.3) {}

public Dog(string name, int age, double length) : this(name, age, length, new Collar()) {}

public Dog(string name, int age, double length, Collar collar)
{
this.name = name;
this.age = age;
this.length = length;
this.collar = collar;
}
public Dog() : this("NoName") {}

public Dog(string name) : this(name, 1) {}

public Dog(string name, int age) : this(name, age, 0.3) {}

public Dog(string name, int age, double length) : this(name, age, length, new Collar()) {}

public Dog(string name, int age, double length, Collar collar)
{
this.name = name;
this.age = age;
this.length = length;
this.collar = collar;
}
I was wondering that can I just use default values for parameters like this, to achieve same result:
public Dog(string name="NoName", int age=1, double length=0.3, Collar collar=new Collar())
{
this.name = name;
this.age = age;
this.length = length;
this.collar = collar;
}
public Dog(string name="NoName", int age=1, double length=0.3, Collar collar=new Collar())
{
this.name = name;
this.age = age;
this.length = length;
this.collar = collar;
}
If yes then is their any use case when we would prefer the 1st way over 2nd?
No description
6 Replies
Pobiega
Pobiega•3d ago
Optional arguments isn't exactly the same as method/constructor overloading, especially when reflected over
Unknown User
Unknown User•3d ago
Message Not Public
Sign In & Join Server To View
Pobiega
Pobiega•3d ago
But if its a type only used internally or similar and that isn't a problem for you, yeah this works
yourFriend
yourFriendOP•3d ago
Hmm... I will see And yes this book is ancient 😅
GoldenFapple
GoldenFapple•2d ago
Your not going to be able to do the last parameter, Collar collar = new Collar() because its not a compile time constant. buuuut, you can do something like this: public Dog() : this("NoName", 1, 0.3, new Collar()) { } This will conflict with this constructor however: public Dog() : this("NoName") { } As that already defines a constructor with no parameters.
yourFriend
yourFriendOP•2d ago
Thanks, have to play around a bit to get used to it.

Did you find this page helpful?