Search code examples
arraysvb.netfunctionfor-loopselect-case

Select case for various input amounts


This is what I have so far;

    Function myChoice(ByVal opt1 As String, ByVal opt2 As String, ByVal opt3 As String, ByVal opt4 As String)

    Dim choose As String
    Dim mynum As Integer

    Randomize()
    mynum = Int(Rnd() * 4 + 1)

    Select Case mynum
        Case 1
            choose = opt1
        Case 2
            choose = opt2
        Case 3
            choose = opt3
        Case 4
            choose = opt4
    End Select

    myChoice = choose

End Function

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    MsgBox(myChoice("Red", "Orange", "Yellow", "Green"))

End Sub

What I am trying to do is not have the ByVal opt1 as string, ByVal op2 ..... If I have say 100 colours, how do I make the function have 100 opt's and there for 100 'case' events without typing it all in?

I thing I may need a loop and maybe an array but other than that, I am stumped.

Thanks.


Solution

  • First make use of the ParamArray parameter. Then use the Random class to get a random item. I would use the top one if you are going to call this method several times in a short time.

    Function ChooseOne(ParamArray opts() As String)
      Static rnd As New Random
      Return opts(rnd.Next(0, opts.Count))
    End Function
    

    Or simpler yet!

    Function ChooseOne(ParamArray opts() As String)
      Return opts(New Random().Next(0, opts.Count))
    End Function