Generate a random number in C#

Generate a random number in C#

Generating random numbers is very easy in C#, there is a Random class in System.Random. I thought I’ll use it to generate random lotto numbers 🙂

This project is available on my Team Foundation Service https://mornewolfaardt.visualstudio.com/DefaultCollection/Random%20Number%20Generator


public void PlayLotto()

{

HashSet lottoNumber = new HashSet();
 do
 {
 Random random = new Random();
 int number = random.Next(1, 46);
 lottoNumber.Add(number);
 }
 while (lottoNumber.Count <= 5);
 lottoNumber.ToList().ForEach(Console.WriteLine);
 Console.Read();

}

 

I decided to use a hashset so that there can only unique numbers, and a do while loop to make sure that the method is recursive until I have 6 numbers