Vb.net Using Boolean variabl to access item in array structure?

R

Rob W

Greetings,

I have a structure as follows:-

Structure Player 'Structure for a player Symbol and
name
Dim Symbol As Char
Dim Name As String
End Structure

Dim Players(1) As Player 'Array for TWO structured player elements

It will only ever as the array is dimensioned hold TWO values, for my
functions I have been passing in an integer variable to select either item 0
or 1.

An example of a function below:-

Function SwapPlayer(ByVal playerTurn As Integer)

'Swap players turn
If playerTurn = 0 Then
playerTurn = 1
Else
playerTurn = 0
End If

'Print whos turn it is
Me.Text = "Your turn " & Players(playerTurn).Name & "(" &
Players(playerTurn).Symbol & ")"

Return playerTurn

End Function

This works fine, however I was recommended to use a Boolean as it will be
more efficient as there will only ever be TWO values, unfortunately a
Boolean is true/false or -1/0 and not 0/1 which would be ideal to access the
array items.

Can anyone suggest the cleanest method to have a Boolean variable used to
pass in a value of 0 or 1 to my functions to select the appropriate array
Item (perhaps a method in the structure)?

I was recommended to use it for simplicity but the only way I can think of
using it relies on conversions and I'm not sure if I would be over
complicating matters.


Thanks
Rob
 
A

Armin Zingler

Rob said:
This works fine, however I was recommended to use a Boolean as it
will be more efficient as there will only ever be TWO values,
unfortunately a Boolean is true/false or -1/0 and not 0/1 which would
be ideal to access the array items.

I wouldn't use a Boolean because of the nature of what it expresses. What is
a true or a false player? I'd identify a player by a number, not by True or
False even if there are two players only.

I wouldn't change the code in this respect. Though, I always recommend
enabling Option Strict.


Oh, and
If playerTurn = 0 Then
playerTurn = 1
Else
playerTurn = 0
End If

can be shortened to:

playerTurn = 1 - playerTurn

;)


Armin
 
R

Rob W

Thanks for the comments, I did think about using the code you suggested but
for code readability I thought to
stick with the IF statements.
 
R

Rob W

Thanks for the tips, I'm quite the newbie to vb.net and only dabbled in
programming on/off throughout the years but really enjoying it now.

I'm going to read through the list of available datatypes now and find out
all about Enums.
Cheers
 
C

Cor Ligthert[MVP]

Rob,

Private Sub SwapPlayer (byVal playerTurner as Boolean)
playerTurn = -PlayerTurner

End Sub
 
C

Cor Ligthert[MVP]

Sorry

Private Sub SwapPlayer (byVal playerTurner as Boolean)
playerTurn = Not PlayerTurner

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top