Reputation: 133
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,
Upvotes: 5
Views: 5680
Reputation: 22151
public class Ball
{
public int Size { get; private set; }
public string Name { get; private set; }
public Ball(string name , int size)
{
Name = name;
Size = size;
}
public Ball(Ball firstBall, Ball secondBall)
{
Name = firstBall.Name + ", " + secondBall.Name;
Size = firstBall.Size + secondBall.Size;
}
}
Upvotes: 5
Reputation: 164281
You can define the addition operator for your type if it makes sense:
public static operator+(Ball rhs, Ball lhs)
{
return new Ball(lhs.Size + rhs.Size);
}
Only do this if it semantically makes sense to add two instances of Ball
together.
Upvotes: 2
Reputation: 54877
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.
Upvotes: 6
Reputation: 43698
You would want to overload the addition operator for Ball
, something like:
public static Ball operator +(Ball left, Ball right)
{
return new Ball(left.Name + right.Name, left.Size + right.Size);
}
Although making a Ball
constructor that takes in 2 Ball
s and adds them is probably more readable, but if you actually want to write new Ball(ball1 + ball2)
then operator overloading would work. If you did it with a constructor, then your code would look like: new Ball(ball1, ball2)
Upvotes: 5
Reputation: 2986
That is about right, just pass the two balls as two parameters to the second overload
Ball BigBall = new Ball(oneBall , anotherBall);
and adjust the overload so it adds the two ball sizes together:
public Ball(Ball firstBall, Ball secondBall){} //I know the arguments have to be added
{
this.size = firstBall.size + secondBall.size;
}
Upvotes: 2