Random Number Generator in C#

In certain scenarios, generating random numbers is a common requirement in applications for various purposes. In C#, the Random class is used for generating random numbers. The Random class represents a pseudo-random number generator, which produces a sequence of numbers that adhere to certain statistical requirements for randomness.

static Random random = new Random();

Next() method

To generate random numbers using the Random class, you can utilize the Next() method. This method returns a non-negative random number. By default, it generates random numbers within the entire range of positive integers.

random.Next();

To limit the range of generated random numbers, you can provide specific parameters to the Next() method. For example, you can specify a maximum value to generate random numbers within a specific range. By setting a maximum value, the generated random number will be between 0 (inclusive) and the specified maximum value (exclusive).

random.Next(10,20);

The above code limit to generate the Random number within the specified range from 10 to 20.

It's important to note that for improved performance, it is recommended to create one instance of the Random object and reuse it to generate multiple random numbers over time. Creating a new Random object each time you need a random number can lead to predictable patterns, as the object is often initialized using the current time as the seed value.

Full Source C#
using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } static Random random = new Random(); private void button1_Click(object sender, EventArgs e) { for (int i = 0; i < 5; i++) { MessageBox.Show(Convert.ToString(random.Next(10,20) )); } } } }

Conclusion

Following these guidelines and using the Random class effectively, you can generate random numbers within specified ranges and improve performance by reusing the Random object in your C# applications.