I am moving from Java to C # and coding some sample programs. Now I came across List of different objects (IUnit), and when I make a call to some value in the list to change its value, it changes all the values. I added a link to the List for other questions.
So, I have the following classes
interface IUnit { int HealthPoints { set; get; } String ArmyType { get; } }
This is the base class that I am calling to create a list of army types (marines / infantry). The implementation is the same; expect the values ββto change inside the class.
public class Infantry : IUnit { private int health = 100; protected String armyType = "Infantry"; public int HealthPoints { get { return health; } set { health = value; } } public String ArmyType { get { return armyType; } }
Then I initialize the list with the following code
List<IUnit> army = new List<IUnit>(); Infantry infantry = new Infantry(); Marine marine = new Marine(); army.Add(Marine);
Then I have a method that simply removes 25 of the health points.
public void ShotRandomGuy(ref List<IUnit> army) { army[0].HealthPoints = army[0].HealthPoints - 25; }
Then I call this method as shown below.
battle.ShotRandomGuy(ref army);
However, he takes 25 from all the objects on this list. How can i stop this? I added a link to the List, so I would think that would remove it from the original list. Do I need to clone a list? Will this work?
Or is it more of a design problem?
Thanks!
source share