5

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,

Vinny
  • 133
  • 1
  • 3
  • 10

5 Answers5

6

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.

Jason Down
  • 21,731
  • 12
  • 83
  • 117
Douglas
  • 53,759
  • 13
  • 140
  • 188
5
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;
    }
} 
Jason Down
  • 21,731
  • 12
  • 83
  • 117
5

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 Balls 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)

CodingWithSpike
  • 42,906
  • 18
  • 101
  • 138
2

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;
}
Kypros
  • 2,997
  • 5
  • 21
  • 27
2

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.

driis
  • 161,458
  • 45
  • 265
  • 341