Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to cast object of type 'System.Random' to type 'System.IConvertible'

Tags:

c#

.net

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;

}
like image 413
NewUser101 Avatar asked Jan 16 '12 15:01

NewUser101


1 Answers

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;
like image 126
vcsjones Avatar answered Oct 05 '22 13:10

vcsjones