C#: Why Are My Random Numbers Not Random?

Question

So I have this code, which is supposed to generate a new random number every time it is called:

        public static int GetSomeRandomNumber(int min, int max)
        {
            Random random = new Random();
            return random.Next(min, max);
        }

In my program, I’m using the above method to let me select five pumpkin colors at random (just don’t ask why):

        enum PumpkinColor
        {
            Red = 0,
            Green = 1,
            Blue = 2
        }

        static void Main(string[] args)
        {
            // write five random pumpkin colors
            for (int i = 0; i < 5; ++i)
            {
                PumpkinColor color = (PumpkinColor)GetSomeRandomNumber(0, 3);
                Console.WriteLine(color);
            }
        }

However, when I run my program, this is the output:

Blue
Blue
Blue
Blue
Blue

Blimey. Not very random now, is it? What gives?

Short Answer

Don’t use a local Random instance in quick loops. Use a shared instance instead:

        private static Random random = new Random();

        public static int GetSomeRandomNumber(int min, int max)
        {
            return random.Next(min, max);
        }

This new implementation now returns:

Green
Red
Red
Blue
Blue

But why does this happen?
And what care do I need to have with static implementations?

Continue reading “C#: Why Are My Random Numbers Not Random?”

C#: How Can We Enumerate An Enum?

Question

How can I enumerate an enum data type in C#?

Say I have this:

    enum PumpkinVariety
    {
        BabyBear,
        FunnyFace,
        HarvestMoon,
        GhostRider,
        BigMax
    }

How can I list this dynamically in any useful way?

Short Answer

If you have a plain vanilla enum, and you don’t have any funky stuff there such as duplicated values, it’s as easy as this:

foreach (PumpkinVariety pv in Enum.GetValues(typeof(PumpkinVariety)))
{
    // do something here
}

If you do have funky stuff going on, that’s another matter…

Continue reading “C#: How Can We Enumerate An Enum?”

C#: string or String?

Question

What’s the deal with the string and other types in C#? I see both string and String all over the place. Same goes with int and Int32 and other types.

For example, I see both:

string text = "Some Text Here";

String text = "Some More Text Here";

What is the difference between them?

Short Answer

None. There is no difference between them. Use the one you like best.

Really? No difference whatsoever?
Why have both forms then? What’s the point?

Well…

Continue reading “C#: string or String?”