So this might sounds like a n00b question, but I want to take 2 classes and merge them together.
Like so :
Ball oneBall = new Ball("red", 20);
Ball anotherBall = new Ball("blue",40);
Ball BigBall = new Ball(oneBall + anotherBall);
BigBall.size() //should say 60 right?
I know you would have something like this
class Ball{
public Ball(string Name , int size){}
// But to merge to of them?
public Ball(Ball firstBall, Ball secondBall){} //I know the arguments have to be added
{}
}
So my question is what is the overload(right?) suppose to look like?
Thanks,
Yes, you can define a constructor overload.
public class Ball
{
public string Name { get; private set; }
public int Size { get; private set; }
public Ball(string name, int size)
{
this.Name = name;
this.Size = size;
}
// This is called constructor chaining
public Ball(Ball first, Ball second)
: this(first.Name + "," + second.Name, first.Size + second.Size)
{ }
}
To merge the two balls:
Ball bigBall = new Ball(oneBall, anotherBall);
Note that you are calling the constructor overload, not the +
operator.
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