How to get random number or generate random password with VB.NET or C#

The simplest way to get random number is to get instance of the Random class and use the "Next" method.
Dim rand As Random=new Random()
rand.Next() gives you a random nonnegative number
rand.Next(23) gives you a random nonnegative number less than integer value (23 for the example)
rand.Next(23, 89) gives you a random nonnegative number in the specified range

With this class you can generate also double values and bytes.

Here is an way for generating random password using guid.
So simple, so effective.

Public Function GetRandomPassword(ByVal length As Integer) As String
Dim rand As String = System.Guid.NewGuid().ToString()
rand = rand.Replace("-", String.Empty)

If length <= 0 OrElse length > rand.Length Then
Throw New ArgumentException("Length must be between 1 and " & rand.Length)
End If

Return rand.Substring(0, length)
End Function

No comments:

Post a Comment