Net-informations.com
SiteMap  | About    

Random Number Generator in C#

In some situations we have to generate Random numbers in our applications for different purposes. In these situations we have to use Random Class in C# for generating the Random numbers. The Random Class in C# represents a pseudo-random number generator, a device that produces a sequence of numbers that meet certain statistical requirements for randomness.

  static Random random = new Random();

The Next() method in Random class returns a nonnegative random number.

  random.Next();

We can limit the generation of Random number by giving a specified range to Next() method.

  random.Next(10,20);

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

To improve performance, create one Random object to generate many random numbers over time, instead of repeatedly creating a new Random objects to generate one random number.




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) ));
			}
		}
	}
}






net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.