I just want add a few points to the other (great) answers.
The name
RandomGeneratorsounds more like a class name rater than a function name. The name should reflect the action / result of the function. A more convenient name would beGenerateRandom.When working with objects implementing
IDisposableit's a good practice to use theUsingkeyword. This way, you are guaranteed that the object is disposed even if an error occurs.I disagree with @ckuhn203 when saying
"begging to return a long". TheBitConverter.ToInt32returns anInteger (Int32), so should the function.An Integer is
32-bit (4 bytes), so the array should be sized3aka.4 - 1. (Think of it as the last index: 0,1,2,3)
Result:
Public Function GenerateRandom() As Integer
Using provider As New RNGCryptoServiceProvider()
Dim data As Byte() = New Byte(4 - 1) {}
provider.GetBytes(data)
Return BitConverter.ToInt32(data, 0)
End Using
End Function