skip to Main Content

I have 2 classes

public class Product
{
    public DateTime Date { get; set; }
    public string Name { get; set; }
    public int Amount { get; set; }
}

public class Campaign
{
    public long CampaignId { get; set; }
    public string CampaignName { get; set; }            
    public List<Product> Products { get; set; }
}

Code:

var campaign = new Campaign();
campaign.CampaignId = Item.CampaignId;
campaign.CampaignId = Item.CampaignId;
campaign.CampaignName = Item.CampaignName;                    
campaign.Products = productList;

campaignList.Add(campaign);
productList.Clear();

When I call productList.Clear(), my "campaign" deletes its campaign.Products.

How can I prevent that from happening?

2

Answers


  1. campaign.Products = new List<Product>(productList);
    
    Login or Signup to reply.
  2. because campaign.Products is the same reference of productList
    they are both pointing to the same list , any action on one will be reflected in the other varialbe
    you need to clone (make another copy of the list) by different ways as follwoing

    campaign.Products = productList.GetClone();
    

    or

    campaign.Products = productList.ToList();  
    

    or

    campaign.Products.AddRange(productList);
    

    check the following url

    https://www.techiedelight.com/clone-list-in-csharp/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search