Alan2
Alan2

Reputation: 24562

How can I randomly generate one of two values for a string?

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

Answers (4)

p.s.w.g
p.s.w.g

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

Yuriy Faktorovich
Yuriy Faktorovich

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

Ryan Bennett
Ryan Bennett

Reputation: 3432

public string GetRandomString()
{
   Random rand = new Random();
   var random = rand.Next(0,1);
   return random == 0 ? "test" : "production";
}

Upvotes: 2

Michael Bray
Michael Bray

Reputation: 15265

Use the Random class:

Random r = new Random();
string a;
if (r.NextDouble() > 0.5) a = "test";
else a = "production";

Upvotes: 1

Related Questions