'how can I preserve my class after list clear

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?



Solution 1:[1]

campaign.Products = new List<Product>(productList);

Solution 2:[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/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JBatstone
Solution 2 Amr Azab