CodePoet CodePoet - 1 month ago 11
C# Question

C#, List Instantiation from existing List?

I'm trying to figure out what is happening in the code snippet below.

In the new list instantiation, it look's like they are referencing the other

coins
List? I have never seen this before, what is the purpose? Sorry if this has already been answer, if so please redirect me. Thank you for your help.

class Program
{
static void Main(string[] args)
{
List<int> coins = new List<int>();
List<int> amounts = new List<int>() { 1, 5, 10, 25, 50 };

Change(coins, amounts, 0, 0, 51);

Console.ReadKey();
}

static void Change(List<int> coins, List<int> amounts, int highest, int sum, int goal)
{
if (sum == goal)
{
Display(coins, amounts);
return;
}

if (sum > goal)
{
return;
}

foreach (int value in amounts)
{
if (value >= highest)
{
List<int> copy = new List<int>(coins); // <<<<<<<
copy.Add(value);
Change(copy, amounts, value, sum + value, goal);
}
}
}

static void Display(List<int> coins, List<int> amounts)
{
foreach (int amount in amounts)
{
int count = coins.Count(value => value == amount);
Console.WriteLine("{0}: {1}",
amount,
count);
}

Console.WriteLine();
}
}

Answer

Here's a description of what the lines do.

 List<int> copy = new List<int>(coins);   // Creates a new list, initializing the values with the values in coins (creating a copy of coins).
 copy.Add(value);  // adds additional value to the copy.
Comments