Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I am writing a small Heads or Tails program using the Random function and receive an Unable to cast object of type 'System.Random' to type 'System.IConvertible' message and am not sure why. Can someone shed a little 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;
                A piece of advice for the future: whenever you receive an error message in C#, check the line it occurred on, make sure you have the correct parameter types / variable types / etc, check for inner exceptions.
– Samuel Slade
                Jan 16, 2012 at 15:25
Random rNum = new Random();
int rrNum = rNum.Next(2, 47);
string result = (rrNum % 2 == 0) ? "Heads" : "Tails";
lblResult.Text = result;
                +1 The only answer that actually looked at the context of the code. It seems indeed unlikely that the OP really intended to convert an object of type Random ;)
– Abel
                Jan 16, 2012 at 15:25

That's because Convert.ToIn32() demands the passed object implements IConvertible.

To retrieve a random number, you need to call the Random.Next() method, like so:

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

You have to assign the value returned from rNum.Next(2,47) to a variable like so:

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

rNum is of type Random. You cannot convert that type to an int.

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

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

The 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 what is returned from the call to Next.

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.