I have just started learning c# and am having a slight problem with a program I'm creating.
I'm creating a program which will create a Number of lotto tickets each with an ID and six randomly generated numbers.
Here is my code for creating the tickets and adding them to a List.
Random random = new Random();// Random number generator
for (int i = 0; i < 1000; i++)
{
do
{
int randomNumber = random.Next(1, 42);// Create randoms numbers between 1 and 42
ticketNumbers.Add(randomNumber);// Add the random numbers to the ticketNumbers SortedSet
}
while (ticketNumbers.Count< 6);// Stop Adding once the six numbers is reached
CTicket firstTicket;
firstTicket = new CTicket(i, ticketNumbers);// Create ticket object pass i's current value as the ticket id and pass the ticketNumbers sorted set as the ticket numbers
ticketList.Add(firstTicket);// Add the firstTicket object to the ticketList
ticketNumbers.Clear();// clear the ticketNumbers list to start again for the next ticket
}
CTicket.Printlist(ticketList);
Here is my function to print the list:
public static void Printlist(List<CTicket> ticketList)
{
foreach (CTicket mytick in ticketList)
{
Console.WriteLine("Ticket ID = {0} ", mytick.m_ticketID);
foreach (int val in mytick.m_ticketNumbers)
{
Console.WriteLine(val);
}
}
}
My problem is when I create a ticket object and add it to the list the print function will only display the id and not the numbers. I have traced the issue to the following:
ticketNumbers.Clear();
It appears that the list is also being cleared for all previous ticketNumbers which are used in creating the objects
Could someone please explain to me why this is happening?