Reputation: 11
Random rd = new Random();
int question;
question = rd.Next(1,2);
if(question ==1)
{
label1.Text = "What is your name?";
}
if(question ==2)
{
label1.Text = "How old are you?";
}
Is there a way to make it shorter? I need to do it this way, but find the shorter option, preferably without ifs.
Upvotes: 0
Views: 56
Reputation: 152616
{completely sarcastic answer}
You want shorter? How about
label1.Text = new Random().Next(1,2) == 1 ? "What is your name?" : "How old are you?";
I'm using this to illustrate that shorter is not always better. Your code compiles, is easy to understand, and generates the right results (modulo the possibility of new Random()
being called multiple times in a tight loop).
Upvotes: 0
Reputation: 15982
You can move your strings to an array and index it by generated number:
string[] texts =
{
"What is your name?",
"How old are you?"
};
int index = rd.Next(0, texts.Length);
label1.Text = texts[index];
Upvotes: 8