strix25
strix25

Reputation: 583

Is it possible to make array size size depended on the atribute value(int)? c#

Now my question is how can I make so when I make new object type Trip, arrayOfPeople will be size of value numberOfRooms?

class Trip
{
    private Person[] arrayOfPeople;

    public Person[] arrayOfPeople get { return arrayOfPeople; }
        set { arrayOfPeople = value; }

}

class Ship  
{

    private int numberOfRooms;


    public int NumberOfRooms
    {
        get { return numberOfRooms; }
        set { numberOfRooms = value; }
    }

}

I was thinking of making numberOfRooms static and then in Trip constructor just setting arrayOfPeople = new Person[Ship.NumberOfRooms] but I am not sure if that is right aproach. Feel free to correct me if I am wrong.

Upvotes: 4

Views: 186

Answers (2)

Stephen P.
Stephen P.

Reputation: 2397

The comments in the code help to answer your question, so check it out :)

public class Trip
{
    // Define a constructor for trip that takes a number of rooms
    // Which will be provided by Ship.
    public Trip(int numberOfRooms)
    {
        this.ArrayOfPeople = new Person[numberOfRooms];
    }

    // I removed the field arrayOfPeople becuase if you are just
    // going to set and return the array without manipulating it
    // you don't need a private field backing, just the property.
    private Person[] ArrayOfPeople { get; set; }
}

public class Ship
{
    // Define a constructor that takes a number of rooms for Ship
    // so Ship knows it's room count.
    public Ship(int numberOfRooms)
    {
        this.NumberOfRooms = numberOfRooms;
    }

    // I removed the numberOfRooms field for the same reason
    // as above for arrayOfPeople
    public int NumberOfRooms { get; set; }
}

public class MyShipProgram
{
    public static void Main(string[] args)
    {
        // Create your ship with x number of rooms
        var ship = new Ship(100);

        // Now you can create your trip using Ship's number of rooms
        var trip = new Trip(ship.NumberOfRooms);
    }
}

Upvotes: 4

gudatcomputers
gudatcomputers

Reputation: 2882

Create a constructor for Trip that takes an integer parameter public Trip(int numberOfPeople) and inside that new up the array like you mentioned arrayOfPeople = new Person[numberOfPeople]()

Upvotes: 2

Related Questions