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;
}
Next
on random returns an integer. So 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With