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

    Question

  • 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; }
            }
            
    }
    
    Now my question is how can I make so when I make new object type Trip, arrayOfPeople will be size of numberOfRooms?

    Friday, April 7, 2017 4:11 PM

All replies

  • Hi Damjan,

    Maybe it's a typo, but your public property in your Trip class should be called ArrayOfPeople, because the private variable is called arrayOfPeople (you did this correctly in Ship class). You'll need to do something like this when setting the ArrayOfPeople for a Trip:

    Ship MyShip = new Ship();
    MyShip.NumberOfRooms = 6;
    
    Trip MyTrip = new Trip();
    MyTrip.ArrayOfPeople = new Person[MyShip.NumberOfRooms];
    


    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Sunday, April 9, 2017 1:42 AM
    Moderator
  • Hi Damjan,

    To make a dynamic array you have to use Heap memory, that is possible by the command "new" in C# language.

    That will work like this:

    TypeOfYourArray yourArrayName = new TypeOfYourArrayElements(sizeOfArray);

    Well, in your case this should be working:

    //first make an object of Ship
    
    Ship nameYourShipObject = new Ship();
    
    //now set a value for numberOfRooms property of it by your written setter
    
    nameYourShipObject.NumberOfRooms = someValueInInt;
    
    //now make an object of Trip
    //"nameYourShipObject.NumberOfRooms" will return the value you set for numberOfRooms property in your Ship Object
    
    Trip nameYourTripObject = new Trip();
    
    //now you have to use "new" command to make your array with the size that need
    
    nameYourTripObject.arrayOfPeaple = new Person[nameYourShipObject.numberOfRooms];

    Now, if you want to do it in your class methods, you can have it there.


    • Edited by Omid.Yazdizadeh Monday, April 10, 2017 11:17 AM just made a mistake
    Sunday, April 9, 2017 4:37 AM
  • Didn't I basically just write the same thing? Only difference is that you have new Person(xxx) , which is wrong ... it should be new Person[xxx]

    ~~Bonnie DeWitt [C# MVP]

    http://geek-goddess-bonnie.blogspot.com

    Sunday, April 9, 2017 5:07 AM
    Moderator