How do I generate a random int number?

前端 未结 30 2594
长发绾君心
长发绾君心 2020-11-21 11:02

How do I generate a random integer in C#?

30条回答
  •  独厮守ぢ
    2020-11-21 11:42

    I wanted to add a cryptographically secure version:

    RNGCryptoServiceProvider Class (MSDN or dotnetperls)

    It implements IDisposable.

    using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
    {
       byte[] randomNumber = new byte[4];//4 for int32
       rng.GetBytes(randomNumber);
       int value = BitConverter.ToInt32(randomNumber, 0);
    }
    

提交回复
热议问题