ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

NextEnum

Generates random enumeration value

Source

public static T NextEnum<T>(this System.Random random)
    where T : struct
{
    Type type = typeof(T);
    if (type.IsEnum == false) throw new InvalidOperationException();

    var array = Enum.GetValues(type);
    var index = random.Next(array.GetLowerBound(0), array.GetUpperBound(0) + 1);
    return (T)array.GetValue(index);
}

Example

public enum AjaxResultEnum
{
Other=0,
Success=1,
Fail=2
}
var value=new Random().NextEnum<AjaxResultEnum>();

Author: pedoc

Submitted on: 4 aug 2015

Language: C#

Type: T

Views: 3634