I'm moving over from Java to C#, and been coding some example programs. Now I have come across a List of different objects (IUnit) and when I make a call to a certain value in the list to change it's value, it changes all the values. I have added a reference to the List - As per other Stack overflow questions.
So I have the following classes
interface IUnit
{
int HealthPoints { set; get; }
String ArmyType { get; }
}
This is the base class I call to create a list of Army Types (Marines/Infantry). The implementation is the same expect a change to the values 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;
}
}
I then 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, which just takes away 25 from the health points.
public void ShotRandomGuy(ref List<IUnit> army)
{
army[0].HealthPoints = army[0].HealthPoints - 25;
}
I then call that method as shown below.
battle.ShotRandomGuy(ref army);
However it takes the 25 away from all the Objects in that List. How would I stop it doing that? I have added a reference to the List, so I would of thought it would of taken it away from the the original List. Do I need to clone the list? Would that work?
Or is it more of a design issue?
Thank you!