.NET 11 Preview - Get Random Integral Numbers
[C#, .NET, .NET 11 Preview]
In a previous post, “Generating Random Values For Other Integral Types In C# & .NET”, we looked at the additional gymnastics needed to generate random values for other integral types, given that the Next method for the Random type was designed for integers.
This means that for a byte, you needed to do something like this:
var randomByte = (byte)Random.Shared.Next(byte.MinValue, byte.MaxValue + 1);
Console.WriteLine(randomByte);
We are doing byte.MaxValue + 1 because the upper bound is not included in the range.
This is no longer necessary.
A new generic method has been introduced for this very purpose: NextInteger().
The equivalent code is as follows:
var randomByte = Random.Shared.NextInteger<byte>();
Console.WriteLine(randomByte);
The same exists for other integral types.
bytesbyteshortushortintuintlongulongnintnuint
A short, for instance, is as follows:
var randomByte = Random.Shared.NextInteger<short>();
Console.WriteLine(randomByte);
Overloads that take a range are also available.
Happy hacking!