Home > Software design >  C# - I have a list of objects, and changing the property in one object changes the property in all o
C# - I have a list of objects, and changing the property in one object changes the property in all o

Time:02-05

I'm trying to make an array of objects I created (Cat) all with random properties, but per the instructions of the assignment, I have to use a separate class (Positions) and call it with one of the Cat's properties. I know this has to do with ref or values, but I can't figure it out...when I iterate through the list and print each one at the end of the loop, everything is fine and random. However, if I iterate through the completed array, all of the properties that are called from another class are the same (the values of the last created objects). I know that I'm changing the actual Positions object that I'm referencing (I don't know if that's the right wording), but I can't for the life of me figure out how to fix it.

This is the relevant part of my Main():

`var rand = new Random();

        // Creating an array for both cat objects and snake objects.
        Cat[] kitty_array = new Cat[6];
        Snake[] snake_array = new Snake[6];

        // Creating the array with 6 cat objects with a random properties.
        int i;
        for (i = 0; i < kitty_array.Length; i  )
        {
            var rand_cat = rand.Next(0, kitties.Count);
            kitty_array[i] = new Cat();
            kitty_array[i].ID = (int)rand.NextInt64(999999);
            kitty_array[i].name = kitties[rand_cat].Remove(0, 4).Replace(" ", "");
            kitty_array[i].age = (double)rand.NextInt64(20);
            kitty_array[i].Breed = (Cat.CatBreed)rand.NextInt64(5);
            kitty_array[i].pos = new Positions(rand.NextInt64(minValue: -10, maxValue: 10),
                rand.NextInt64(minValue: -10, maxValue: 10), rand.NextInt64(minValue: -10, maxValue: 10));
            Console.WriteLine(kitty_array[i].ToString());
        }`

And per the Console.Writeline at the end of the loop, this is my output (which is exactly what I'm looking for).

Name: Simba ID: 286969 Age: 8 Breed: British_Short_hair Pos X:-2 Pos Y:-6 Pos Z:4

Name: Rocky ID: 227103 Age: 5 Breed: Ocicat Pos X:-7 Pos Y:-11 Pos Z:7

Name: Patches ID: 899494 Age: 16 Breed: Bengal Pos X:-9 Pos Y:-8 Pos Z:9

Name: Phoebe ID: 210697 Age: 11 Breed: Himalayan Pos X:-14 Pos Y:-11 Pos Z:5

Name: Chloe ID: 639025 Age: 7 Breed: Ocicat Pos X:-14 Pos Y:-8 Pos Z:0

Name: Orion ID: 825255 Age: 2 Breed: Ocicat Pos X:-12 Pos Y:-7 Pos Z:-3

However, when I iterate through the array with:

`foreach (var VARIABLE in kitty_array)
       {
            Console.WriteLine(VARIABLE.ToString());
        }
`

I get this (all the Pos share the same properties which is the final property output of the creating loop):

Name: Simba ID: 286969 Age: 8 Breed: British_Short_hair Pos X:-12 Pos Y:-7 Pos Z:-3

Name: Rocky ID: 227103 Age: 5 Breed: Ocicat Pos X:-12 Pos Y:-7 Pos Z:-3

Name: Patches ID: 899494 Age: 16 Breed: Bengal Pos X:-12 Pos Y:-7 Pos Z:-3

Name: Phoebe ID: 210697 Age: 11 Breed: Himalayan Pos X:-12 Pos Y:-7 Pos Z:-3

Name: Chloe ID: 639025 Age: 7 Breed: Ocicat Pos X:-12 Pos Y:-7 Pos Z:-3

Name: Orion ID: 825255 Age: 2 Breed: Ocicat Pos X:-12 Pos Y:-7 Pos Z:-3

I've tried playing around so many times with ref and getting and setting, but I'm losing my mind with it. I know I'm changing the actual Positions class or the instantiation of it, but I don't know how to fix it (I've tried making copies, etc)...These are my classes. If somebody could explain this to me I'd be forever grateful. I've been looking everywhere but I'm at a loss.

`public class Positions
    {
        private static double x;
        private static double y;
        private static double z;

        // For declaring the Position
        public Positions(double x, double y, double z)
        {
            Positions.x = x;
            Positions.y = y;
            Positions.z = z;
        }

        // Setting and Getting and clamping to -10 and 10 if it's lower or higher than said number.
        public double X
        {
            get => x;
            set => Positions.x = Math.Clamp(value, -10, 10);
        }

        public double Y
        {
            get => y;
            set => y = Math.Clamp(value, -10, 10);
        }

        internal double Z
        {
            get => z;
            set => z = Math.Clamp(value, -10, 10);
        }

        // method for taking user input and updating the position by said input.  
        public void move(double dx, double dy, double dz)
        {
            x = Math.Clamp(x   dx, -100, 100);
            y = Math.Clamp(y   dy, -100, 100);
            z = Math.Clamp(z   dz, -100, 100);
        }
    }

    // Creating the Animal class with associated properties
    public class Animal
    {
        public int ID { get; set; }
        public string name { get; set; }
        public double age { set; get; }

        public Positions pos = new Positions(0,0,0);


        public void Move(double dx, double dy, double dz)
        {
            pos.move(dx, dy, dz);
        }

        // prints off the properties
        public override string ToString()
        {
            return age   name   ID;
        }


    }

    // creating a subclass cat from the animal class.  
    public class Cat : Animal
    {
        
        // enum for different breeds
        public enum CatBreed
        {
            Abyssinian = 0,
            British_Short_hair = 1,
            Bengal = 2,
            Himalayan = 3,
            Ocicat = 4,
            Serval = 5
        }

        private CatBreed breed;

        public CatBreed Breed
        {
            get { return breed; }
            set => breed = value;
        }





`


CodePudding user response:

members x,y,z are declared as static in Positions class, that's why they are shared across the Positions class instances and returns you the last modified values if you want to keep values unique per instance, you have to take off the static declaration

  • Related