Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random.Next not working? [duplicate]

Tags:

c#

random

system

I'm trying to make a random room selector and Random.Next seems to not be working, please help!

List<string> rooms = new List<string>();
rooms.Add(room1);
rooms.Add(room2);   
int index = Random.Next(rooms.Count);
System.Console.WriteLine(rooms[index]);

The systems I am using (I think this may be the problem)

Using System
Using System.Collections.Generic
Using.Collections

Using.Collections is greyed out.

like image 952
user7717595 Avatar asked Apr 09 '17 13:04

user7717595


People also ask

How does random next work?

Random. Next generates a random number whose value ranges from 0 to less than Int32. MaxValue. To generate a random number whose value ranges from 0 to some other positive number, use the Random.

How do you pick a random number in C#?

To generate random numbers in C#, use the Next(minValue, MaxValue) method. The parameters are used to set the minimum and maximum values. Next(100,200); We have set the above method under Random() object.

What library is random in C#?

NET class library provides functionality to generate random numbers in C#.


1 Answers

your issue is that you want to call the Next method directly on the Random class, unfortunately, there is no static Next method for the Random class.

int index = Random.Next(rooms.Count);

you'll need to make an instance of the Random generator, in order to invoke the Next method.

Example:

Random rand = new Random();
int index = rand.Next(rooms.Count); 
System.Console.WriteLine(rooms[index]);

further reading:

How do I generate a random int number in C#?

like image 186
Ousmane D. Avatar answered Oct 30 '22 22:10

Ousmane D.