Reputation: 24562
I have a variable named a that I am currently giving the value:
var a = "test";
How can I make it so that the variable gets the value of "test" or "production" at random each time it is set ?
Upvotes: 0
Views: 398
Reputation: 149010
You'd need to use the Random
class:
var r = new Random();
var a = r.Next(2) == 1 ? "test" : "production";
Here's another trick that's useful if you have more than one string you want to select randomly:
var r = new Random;
var strings = new[] { "test", "production" };
var a = strings[r.Next(strings.Length)];
Upvotes: 11
Reputation: 68667
var a = (new Random()).Next(2) == 0? "test" : "production";
If you're running this repeatedly, you'll want to store the Random instance and reuse it.
Upvotes: 3
Reputation: 3432
public string GetRandomString()
{
Random rand = new Random();
var random = rand.Next(0,1);
return random == 0 ? "test" : "production";
}
Upvotes: 2
Reputation: 15265
Use the Random
class:
Random r = new Random();
string a;
if (r.NextDouble() > 0.5) a = "test";
else a = "production";
Upvotes: 1