0

I have this object list named list<product> A within class USER, there is also a list<USER> in the main program we name list C.

List A will be updated every time the user buya something from another list<product> B (this on is on the main class) that contains every product we have and some additional information on how much it costs (based on user age) and when it was bought (which variable exist from the product class, although it's empty when it's inside list A as I only want to save the product name, and product description in list B).

If the product the user bought does not exist in list B then it will print "no product exists". If it exist it will add the product the user bought to List A. The program does not run as intended, the add to list A is running fine (although it somehow updates the list B product with the same name?), if the user buys a different product but if it's the same product the list A will update every list in list product???

Here is the add product code:

public static Produk Sehat = new Produk("Sehat Bersama",EnumJenisKesehatan.Kesehatan
        ,EnumFrequensi.Bulanan,"Claim Perawatan kelas 1");

public static Produk SehatExtr = new Produk("Sehat Extra", EnumJenisKesehatan.Kesehatan
        , EnumFrequensi.Bulanan, "Claim Perawatan VIP"); 

public static List<Produk> allprod = new List<Produk>()
        { Sehat,SehatExtr};

Here is the add product to list (with the assumption that we've got the product we want to add, and the user that bought it).

Tempuser._produk.Add(produk);

Here is the one that adds the price in user class to the product list (again with the asumption that we've already got the product from the user list[product]).

int price;

if (User._age < 20)
{
    price= 200000m;
    product._price= price;
}
else
{    
    price=300000m;  
    product._price=price; 
}

I even made the product list into a dictionary (with product as value and and ID as the key) but the code still updates every product with the same name and my senior tends to get mad at me, if I ask her this kind of question....

Please someone is there some kind of solution to this?

4
  • You are likely sharing the same object (reference) between 2 lists, so the price / name / or anything else will be reflected in both lists (as its the same object). Its hard to comment further as we would need to see more code to determine the exact place of the mistake and the true nature of the problem Commented Mar 20, 2020 at 8:29
  • When you assign a product of list B to list A, you're assigning a reference to the product so if you change it in list A the change will be visible in list B, too. If copying is what you need then clone the object in B to list A. Commented Mar 20, 2020 at 8:31
  • @AlexDomenici is there any document explaining clone ? or can you explain it in a code? Commented Mar 20, 2020 at 8:40
  • @AhmadMahdi take a look at learn.microsoft.com/en-us/dotnet/api/… Commented Mar 20, 2020 at 8:42

2 Answers 2

1

You are likely sharing the same object (reference) between 2 lists, so the price / name / or anything else will be reflected in both lists (as it's the same object).

You can think of a reference as a piece of paper which has the address of a physical location of stuff. When you are adding the reference to a list, or copy it. You are just coping the that piece of paper (the address). When you change a property, it looks up the actual physical location and it changes the stuff for everyone.

What you will need to do is clone your product. There are lots of ways to do this, some easier than others. However the most fundamental way is just copy the properties and state. Such that the internal state is the same.

var newProduk = new Produk() 
                     {
                         Price = produk.Price,
                         Name = produk.Name,
                         ...
                         // the rest of your state and properties
                     };

Tempuser._produk.Add(newProduk );
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you now i understand how it goes
0

When you assign a product of list B to list A, you're assigning a reference to the product, not a copy of it, so when you change it in list A you're actually changing the same product in list B, too.

If copying is what you need then clone the object in B to list A. Here's an example of how to clone an object:

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var listA = new List<MyObj>();
        var listB = new List<MyObj>();

        listB.Add(new MyObj{Name="John", Surname="Smith"});
        listA.Add((MyObj)listB[0].Clone());

        listA[0].Name = "Michael"; 

        Console.WriteLine(listA[0].Name);
        Console.WriteLine(listB[0].Name); 
    }
}

class MyObj: ICloneable
{
    public string Name {get;set;}
    public string Surname {get;set;}

    public object Clone() 
    {
        return (MyObj)this.MemberwiseClone();
    }
}

You can run this sample in https://dotnetfiddle.net to see it in action.

Hope this helps :)

4 Comments

To future readers. ICloneable is kind of a dirty interface these days and similarly MemberwiseClone (both for various reasons), there are many blogs about its pros and cons.
@MichaelRandall please elaborate on the "kind of a dirty interface".
Alex there are plenty of resources on the issue (not to shade on your answer), it comes down to the nature of what it does, whether its deep or shallow and its up to the implementer. These days we tend to make things more explicit
Michael there are pros and dcons to both solutions. Even the one you proposed, perfectly functional, should be provided only as a class method otherwise changes to the object (i.e. adding a new property) would break the code where the cloning is used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.