Using the Using StatementThe 7 Steps of Software Development Case Study - Chapter I

The .NET Random Object

May 21st, 2007

Do you feel lucky?In VB6, and in MS-BASICs going back for probably 30 years, you would use the Rnd function to get a pseudo random number and you would use the Randomize statement before it to ’seed’ the values. This is replaced in VB.NET with the new Random object.

Using this object is simple. You create a new instance of the object, like so

 

 

 

Dim Dice As New Random

And use the Next function to get a random integer in a specified range.

Dim Result As Integer = Dice.Next(1,7)

Note that the lower bound is inclusive, the value given is the lowest value returned, while the upper boundary is exclusive, one integer higher than the highest value you want the function to return.

The Random object also provides functions for returning an array of random bytes or a double number between 0.0 and 1.0.

Unlike previous versions of MS-BASICs, the timer based seed value is the default so you no longer need a Randomize statement. However, you can use an integer value when creating the object instance to get the same value sequence all the time which can be valuable during testing.

One important trick you can use with the Random object is to create an instance at the module or application level, not the routine level. The standard rule when declaring a variable is to limit the scope but this is an exception to the rule. By creating it at a higher level, the seed does not need to be regenerated on each call, which improves performance and helps insure a more random sequence, particularly if many random numbers are being generated quickly in a loop.

Here’s a simple playing card class code example that you can experiment with by making your own poker or blackjack game. In additon to the Random object, this example also uses the generic dictionary and shared members that I’ll be covering in a later column.

Public Class PlayingCard

    Private Shared Suits As Dictionary(Of Integer, String)
    Private Shared Values As Dictionary(Of Integer, String)
    Private Shared CardSelect As New Random

    Private _suit As String
    Private _value As String

    Public Sub New()
        LoadDictionaries()
        _suit = Suits(CardSelect.Next(1, 5))
        _value = Values(CardSelect.Next(1, 14))
    End Sub

    Private Sub LoadDictionaries()
        If Suits Is Nothing Then
            Suits = New Dictionary(Of Integer, String)
            With Suits
                .Add(1, “Hearts”)
                .Add(2, “Diamonds”)
                .Add(3, “Clubs”)
                .Add(4, “Spades”)
            End With
        End If
        If Values Is Nothing Then
            Values = New Dictionary(Of Integer, String)
            With Values
                .Add(1, “Ace”)
                .Add(2, “Deuce”)
                .Add(3, “Three”)
                .Add(4, “Four”)
                .Add(5, “Five”)
                .Add(6, “Six”)
                .Add(7, “Seven”)
                .Add(8, “Eight”)
                .Add(9, “Nine”)
                .Add(10, “Ten”)
                .Add(11, “Jack”)
                .Add(12, “Queen”)
                .Add(13, “King”)
            End With
        End If
    End Sub

    Public ReadOnly Property Suit() As String
        Get
            Return _suit
        End Get
    End Property

    Public ReadOnly Property Value() As String
        Get
            Return _value
        End Get
    End Property

End Class
Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Entry Filed under: Code Examples


Rate This Article:

Not That GoodCould Be BetterOKGoodGreat (No Ratings Yet)
Loading ... Loading ...

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Visit Me At My New Site, Programming In C#

Most Popular Articles

Highest Rated Articles

Categories

Most Recent Articles

Feeds

 Subscribe in a reader

To subscribe by e-mail
Enter your address here

Delivered by FeedBurner

VB Opportunities

Archives