From a401aabee8fd74d1a66b86b6258ea3400a298fe8 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Sun, 7 Mar 2021 14:20:01 +0000 Subject: [PATCH] Add Random.Next() where T : Enum --- X10D/src/RandomExtensions/RandomExtensions.cs | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/X10D/src/RandomExtensions/RandomExtensions.cs b/X10D/src/RandomExtensions/RandomExtensions.cs index f9a8bc2..4da372c 100644 --- a/X10D/src/RandomExtensions/RandomExtensions.cs +++ b/X10D/src/RandomExtensions/RandomExtensions.cs @@ -11,6 +11,27 @@ namespace X10D.RandomExtensions { internal static readonly Random Random = new(); + /// + /// Returns a random value that defined in a specified enum. + /// + /// The instance. + /// An enum type. + /// + /// A value at index n where n = . + /// + /// is . + public static T Next(this Random random) + where T : struct, Enum + { + if (random is null) + { + throw new ArgumentNullException(nameof(random)); + } + + var values = Enum.GetValues(typeof(T)); + return (T)values.GetValue(random.Next(values.Length))!; + } + /// /// Returns either or based on the next generation of the current /// .