1

I'm having a problem when using variables in object names.

I have a Public class which is called "Tank" In that class, there is a public property called "direction" of an integer type.

I keep getting the error: "Tank is a type and cannot be used as an expression" What I'm doing wrong here ?

Public Class mainroutines()

' Create Instances of tank  

Private Tank1 As New Tank()
Private Tank2 As New Tank()

'Loop trough objects and set the property value

dim i as integer
For i = 1 to 2
Tank(i).direction = 1
next i

End class
0

3 Answers 3

2

You don't have an array of Tanks:

Public Class mainroutines()

' Create Instances of tank  

Private Tank1 As New Tank()
Private Tank2 As New Tank()

'Loop trough objects and set the property value
Dim tanks() As Tank

tanks(0) = Tank1
tanks(1) = Tank2

For i As Integer = 1 To 2
   tanks(i).direction = 1
next

End class

If you're using Visual Studio 2008 then you could use:

Private Tank1 As New Tank() With { .Direction = 1}
Private Tank2 As New Tank() With { .Direction = 1}

So you don't need the For loop at all.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answers The loop was just ment as an example. I'm writing a game and I need a tank for player 1 and one for player 2. player is a variable of the integer type and is 1 or 2 depending on the player which is in control In my code I often need to change the direction, or the x,y coordinates of the tank and I like to reference to the tank as Tank(player).direction or Tank(player).X += 5 or Tank(player).livesleft -= 1 I'll have to test your answers
1

Well, Tank(i) is not equivalent to Tank1. You would need to make a list of tanks, add your instances to it, and access them that way.

Public Class mainroutines() 

' Create Instances of tank '  

Dim allTanks As List(Of Tank) = New List(Of Tank) 
allTanks.Add(New Tank())
allTanks.Add(New Tank())

'Loop through objects and set the property value '

dim i as integer 
For i = 1 to 2 
allTanks(i).direction = 1 
next i 

Comments

0

@ Jball

It needed a small correction and your example worked just fine ! Exactly what I needed !

Dim alltanks As List(Of Tank) = New List(Of Tank)

Thanks a lot for your help !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.