Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# join 2 or more classes together?

Tags:

c#

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,

like image 275
Vinny Avatar asked Jan 22 '12 19:01

Vinny


1 Answers

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.

like image 124
Douglas Avatar answered Sep 26 '22 16:09

Douglas