Cannot overlay object of type "System.Random" on type "System.IConvertible"

I write a small Heads or Tails program using the Random function, and get Unable for a cast object of type "System.Random" to enter a System.IConvertible message, and I don’t know why. Can someone shed some light. Thanks.

protected void Button1_Click(object sender, EventArgs e) { Random rNum = new Random(); rNum.Next(2, 47); int rrNum = Convert.ToInt32(rNum); string result; result = (rrNum % 2 == 0) ? "Heads" : "Tails"; lblResult.Text = result; } 
+7
source share
4 answers

Next when randomly returning an integer. Therefore, the correct code is:

 Random rNum = new Random(); int rrNum = rNum.Next(2, 47); 

So, from there there is no need to convert rNum to an integer.

 Random rNum = new Random(); int rrNum = rNum.Next(2, 47); string result = (rrNum % 2 == 0) ? "Heads" : "Tails"; lblResult.Text = result; 
+7
source

This is because Convert.ToIn32() requires the passed object to implement IConvertible .

To get a random number, you need to call the Random.Next() method, for example:

 Random rNum = new Random(); int YourRandomNumber = rNum.Next(2, 47); 
+1
source

You must assign the value returned from rNum.Next(2,47) to a variable as follows:

 int rrNum = rNum.Next(2,47); 

rNum is of type Random . You cannot convert this type to int .

rNum.Next(2,47) returns the int you want. If you look at the documentation for Random.Next , you will see that its signature is of the type:

 public virtual int Next(int minValue, int maxValue); 

int in public virtual int is the return type of the method. You can use this information to determine what type of variable you need to store, which is returned from the call, to Next .

0
source

Just as the error message indicated, you cannot convert an instance of System.Random, in this case Int.

-2
source

All Articles