Friday, March 23, 2012

Pick a Random Enum in C# (Better than my old post)

static T RandomEnum() {
           if ( typeof( T ).IsEnum ) {
                var names = Enum.GetNames( typeof( T ) );
                return ( T )Enum.Parse( typeof( T ), names[ threadsafeRandom.Value.Next( 0, names.Length ) ] );
            }
            return default( T );
}

static readonly ThreadLocal threadsafeRandom = new ThreadLocal( () => new Random( RandomSeed() ) );

No comments :