You can generate a truly random 5 digit number in C# using the RNGCryptoServiceProvider
class in the System.Security.Cryptography
namespace. Here's an example code block:
main.cs337 chars13 lines
In this example, we're creating a new instance of the RNGCryptoServiceProvider
class and using its GetBytes
method to generate a byte array with 4 random bytes. We then use the BitConverter.ToInt32
method to convert those bytes to an integer, and take the modulo of that integer with 100000 to ensure we have a 5-digit number.
Note that this approach generates truly random numbers using cryptographic methods, rather than using a pseudorandom number generator like Random
, which is not suitable for use in cryptographic or security-sensitive applications.
gistlibby LogSnag