I am getting a problem with my list getting overwritten when trying to update it. I did find quite many references about this, but still can't apply them to my case.
Most of them suggest moving the declaration of variable inside a loop, but I am not using any loops at this stage.
There is a class based on the interface named Persons. I want to create a new Person when clicking the "add" button, the name of person is taken from the textbox.
The interface and the class for it:
interface IPerson
{
//int getId();
String GetFirstName();
//String getLastName();
//DateTime getDateOfBirth();
//int getHeight();
}
public class Person: IPerson
{
//public double MaximumValue;
public string GetFirstName()
{
return Form1.newName;
}
}
Button click:
private void btnAdd_Click(object sender, EventArgs e)
{
newName = txtName.Text;
//Person newPerson = new Person();
//newPerson.GetFirstName();
PersonCollection.ThisPersonCollection.Add();
}
Form Load:
private void Form1_Load(object sender, EventArgs e)
{
PersonCollection.ThisPersonCollection = new PersonCollection();
PersonCollection.ThisPersonCollection.Create();
}
Person collection class:
class PersonCollection
{
public static PersonCollection ThisPersonCollection;
private static object _lock = new object();
public static List<Person> _persons;
public static List<Subscriber> _subscribers;
private static System.Timers.Timer _timer = new Timer();
}
Add method in PersonCollection class
public void Add()
{
lock (_lock)
{
Person newPerson = new Person();
newPerson.GetFirstName();
_persons.Add(newPerson);
}
}
I tried playing with static\non-static for all variables and classes, I tried to create a
newPerson = new Person();
in button click method and in Add method from the class, I tried to first add the new Person and only then alter it's values, I tried to create a Person as a method:
public Person NewPerson()
{
Person newPerson = new Person();
newPerson.GetFirstName();
return newPerson;
}
But neither of this did anything. From what I read, I do understand that when trying to add a new Person, instead I am overwriting all existing ones, because all list objects use same reference. But I can't get how to fix this.
Please help,
Evgenie