Is it possible for the size of the array size to depend on the value of the attribute (int)? WITH#

Now my question is: how can I do this when I create a new type of Trip object, will arrayOfPeople be the size of the numberOfRooms value?

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 about making numOfRooms static, and then in the Trip constructor just set arrayOfPeople = new Person [Ship.NumberOfRooms], but I'm not sure if this is aproach right. Feel free to correct me if I am wrong.

+4
source share
2 answers

Comments in the code will help 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 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 number of rooms
        var trip = new Trip(ship.NumberOfRooms);
    }
}
+4
source

Create a constructor for Trip, which takes an integer parameter public Trip(int numberOfPeople)and inside this new array, as you mentionedarrayOfPeople = new Person[numberOfPeople]()

+2
source

Source: https://habr.com/ru/post/1674327/


All Articles