tags:

views:

313

answers:

4

Am I looking too far to see something as simple as pick a number: 0 or 1?

  Random rand = new Random();

  if (rand.NextDouble() == 0)
  {
   lnkEvents.CssClass = "selected";
  }
  else
  {
   lnkNews.CssClass = "selected";
  }
+16  A: 

If you want 50/50 probability, I suggest:

            Random rand = new Random();

            if (rand.NextDouble() >= 0.5)
            {
                    lnkEvents.CssClass = "selected";
            }
            else
            {
                    lnkNews.CssClass = "selected";
            }
Mitch Wheat
Yeap- currently the probability is nowhere near that. :-).
RichardOD
+3  A: 

Random.NextDouble() will select any double number from 0 but less than 1.0. Most of these numbers are not zero, so your distribution will not be as even as you expect.

Timbo
"not be as even as you expect" is understatement of the year. Virtually all generated results would be 1.
Godeke
For the record: I've never seen a zero being returned by a PRNG. And I've tested them a lot a few months ago :-)
Joey
+19  A: 
            Random rand = new Random();

            if (rand.Next(0, 2) == 0)
            {
                    lnkEvents.CssClass = "selected";
            }
            else
            {
                    lnkNews.CssClass = "selected";
            }

Random.Next picks a random integer between the lower bound (inclusive) and the upper bound (exclusive).

JDunkerley
This is the one I would go for.
RichardOD
Note: Random rand = new Random(); should, ideally, be stuck somewhere else, not right above the call to rand.Next. Ideally, it should be initialized once.
Brian
+2  A: 

It seems like what you're wanting to do (choose between two values) is more clearly expressed by using the Next method, instead of the NextDouble method.

const int ExclusiveUpperBound = 2;
if (new Random().Next(ExclusiveUpperBound) == 0)

The value produced is "greater than or equal to zero, and less than" ExclusiveUpperBound.

bdukes