Iwan Raflis Iwan Raflis - 3 years ago 94
C# Question

List is getting reset although it has been saved

My job right now is to create a Recipe Book. The Recipe class has name and list of Ingredient(Zutaten) as properties. When I create a recipe for the 1st time and save it in a List of recipe, it has the correct data.
1) Why as i entered my 2nd code part below to create 2nd recipe, the 1st recipe List of Ingredient(Zutaten) is emptied? (I didn't do anything to alter the recipe data)
2) Why as i save the 2nd recipe in the List of recipe, the 1st recipe has the same List of Ingredient of the 2nd Recipe?

public Rezept(String name, List<Zutaten> ingredient)
this.name = name;
this.ingredient = ingredient;

this is 1 of my class Rezept.

public partial class Form1 : Form
public Form1()
Verwaltung ve = new Verwaltung();
private List<Rezept> rezept = new List<Rezept>();
List<Zutaten> z = new List<Zutaten>();

String na;
Zutaten zutat;
int m;

private void buttonAdd_Click(object sender, EventArgs e)


na = tBName.Text;
m = Convert.ToInt32(tBMenge.Text);
switch (comboBoxUnit.SelectedItem.ToString())
case ("Gramm"):
zutat = new Zutaten(na, m, Einheit.Gramm);
case "Litre":
zutat = new Zutaten(na, m, Einheit.Litre);
case "Stueck":
zutat = new Zutaten(na, m, Einheit.Stueck);

ListViewItem item = new ListViewItem();
item.Text = na;
switch (zutat.getEinheit)
case Einheit.Gramm:
case Einheit.Litre:
case Einheit.Stueck:



and this is how i create a new list of Zutaten everytime. And to create a new Rezept is, i used this method

Rezept r = new Rezept(textBoxName.Text, z);

z is the List of the Zutaten that i have created in 2nd code.

Answer Source

Because you're using the same list in both instances.

You have a single list. A reference to that list is saved in each recipe. Each time you click add, it clears out the list and adds a new item.

According to your comment, you have 2 buttons, one to add an ingredient, and one to finish the recipe. You should never be clearing out (removing) an ingredient list. You should create a new list whenever you create the Recipe.

private List<Rezept> recipes = new List<Rezept>();
private List<Zutaten> ingredients = new List<Zutaten>();

private void AddIngredient()
    var i = new Zutaten();

private void AddRecipe()
    var r = new Rezept("My Recipe", ingredients);
    ingredients = new List<Zutaten>();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download