user3514541
user3514541

Reputation: 23

C# - Using type as instance variable

I am following a guide on C# programming (The C# Players Guide 2nd Edition) and am stuck on understanding classes (page 131).

The exercise states that I should construct a Ball class that should have a size/radius as well as a colour instance variable. Now I have previously created a Colour class (that has two constructors with one accepting four ushort and one accepting three ushort types) but it is wanting me to use the Colour type I just created.

I have no idea how to do this! So far I have:

private int size;
private int radius;
private int throwCount;
private Colour colour;

public Ball(int size, int radius, Colour colour)
{
    this.size = size;
    this.radius = radius;
    this.colour = colour;
}

If I create a ball I don't know how to correctly use the colour parameter.

Ball myBall = new Ball(1,2, ?)

Can you guys help me out please and just tell me if I am doing this right?

Thanks in advance from a pure newbie!

Upvotes: 0

Views: 312

Answers (2)

Peter B
Peter B

Reputation: 24280

First you create a new Colour object, which you then pass to the Ball constructor method:

var colour = new Colour( ... );  // provide suitable parameters
Ball myBall = new Ball(1, 2, colour);

Or you can even do it in one line of code:

Ball myBall = new Ball(1, 2, new Colour( ... ));  // provide suitable parameters

Upvotes: 4

yan yankelevich
yan yankelevich

Reputation: 945

Here you have at least two choices :

Either they want you to instantiate the ball as you instantiate the colour :

Ball myBall = new Ball(1,2, new Colour(1,2,3));

Either they want you to instantiate it before the ball and reuse it after, this way you can use the same instance of Colour for different balls :

Colour myColor = new Colour(1,2,3)
Ball myBall = new Ball(1,2, myColor );
Ball myOtherBall = new Ball(4,2, myColor );

Upvotes: 3

Related Questions