Random::NextBytes Method
Fills the elements of a specified array of bytes with random numbers.
Assembly: mscorlib (in mscorlib.dll)
Parameters
- buffer
- Type: array<System::Byte>
An array of bytes to contain random numbers.
| Exception | Condition |
|---|---|
| ArgumentNullException | buffer is nullptr. |
Each element of the array of bytes is set to a random number greater than or equal to zero, and less than or equal to MaxValue.
To generate a cryptographically secured random number suitable for creating a random password, for example, use a method such as RNGCryptoServiceProvider::GetBytes.
Notes to InheritorsStarting with the .NET Framework version 2.0, if you derive a class from Random and override the Sample method, the distribution provided by the derived class implementation of the Sample method is not used in calls to the base class implementation of the NextBytes method. Instead, the uniform distribution returned by the base Random class is used. This behavior improves the overall performance of the Random class. To modify this behavior to call the Sample method in the derived class, you must also override the NextBytes method.
The following example demonstrates how to use the NextBytes method to fill an array of bytes with random byte values.
#using <System.DLL> using namespace System; int main() { Random^ rnd = gcnew Random; array<unsigned char>^b = gcnew array<unsigned char>(10); rnd->NextBytes( b ); Console::WriteLine( "The Random bytes are: " ); for ( int i = 0; i < 10; i++ ) { Console::Write( i ); Console::Write( ":" ); Console::WriteLine( b[ i ] ); } }
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.