How to Generate Random Numbers in C#

Sometimes developers need to generate random numbers, so Microsoft has included a builtin class in the C# language.

For generating a random number, you can use the Random class in C# that resides in the "System" Namespace.

Random

Step 1: Create a new Empty Website named "Website1".

new Empty Website

And add the Web form named "Deafult.aspx" into it.

Web form

Step 2: Add a button to the "Deafult.aspx" page with the Text "Generate Random Number" and a click event.

Deafult

Step 3: Write the code on button click event.

  • Create an object of the "Random" class.
    1. Random r = new Random(); 
  • To get the next value of the random object and save the output in an int variable named "num".
    1. int num=r.Next(); 
  • Print the "num" variable.
    1. Response.Write(num.ToString()); 
    num

Step 4: After running the page.

running the page
After clicking the button, first I got "369593053" as the random number.

And the second time, I got "820031117" as the random number.

 	The name of a character array is actually a pointer to the first element of the array.

Note: You can also set the range of random numbers. In my future article you can see that.

Up Next
    Ebook Download
    View all
    Learn
    View all