Random Enum in C#

I wrote this because.. well.. I can. 8D

If you use this code, please give Protiguous some credit. (Too bad adSense doesn’t allow one to ask for clicks. Because that’d be cooler!)


  1. Initialize a newly seeded rng with an overkill of LINQ.
  2. Initialize a thread safe access control.
  3. Generate a list of names for each defined enum.
  4. … and return one of those enums.

Here is some untested sample code:

enum ourEnums { One, Two, Three, Four, Five };

//I know we could use a for loop, but I love foreach so much more..
foreach ( var i in Enumerable.Range( 0, 10 ) ) {
Console.WriteLine( RandEnum() );

Note: If there are any uppercase/lowercase/typos… let’s just blame it on blogspot/browser/politics/etc… as always: It Works On My Machine.

And here is my sample code for returning a random enum in C#:

namespace Examples {
using System;
using System.Linq;
using System.Threading;

public class Example {

private static readonly Random oti = new Random( Guid.NewGuid().ToByteArray().Sum( b => b * b.GetHashCode() ) );

private static readonly ReaderWriterLockSlim otia = new ReaderWriterLockSlim( LockRecursionPolicy.SupportsRecursion );

public static T RandEnum() {
if ( !typeof( T ).IsEnum ) { return default( T ); }

var names = Enum.GetNames( typeof( T ) );
try { otia.EnterWriteLock(); return ( T )Enum.Parse( typeof( T ), names[ oti.Next( 0, names.Length ) ] ); }
finally { otia.ExitWriteLock(); }


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s