views:

1180

answers:

1

Hi can someone show me an example of a multidimensional associative array in vb.net. Need array to hold peoples name, there age and a few other settings. Want to be able to use a Dictionary to use People.Add.

Thanks

--Mark

+2  A: 

Think OOP. You should use a class to associate the properties with each other. Example:

Class Person

   Private _name as String
   Private _age as Integer

   Public ReadOnly Property Name
      Get
         Return _name
      End Get
   End Property

   Public ReadOnly Property Age
      Get
         Return _age
      End Get
   End Property

   Public Sub New(name As String, age as Integer)
      _name = name
      _age = age
   End Sub

End Class

Now you can put the people in a dictionary:

Dim people As New Dictionary(Of String, Person)()
people.Add("John", new Person("John", 42))
people.Add("Jane", new Person("Jane", 12))
Guffa
Agreed, but slightly off topic do you think it should immediately be a class? Just from the problem example person isn't any deeper than a related set of data. Isn't this why structs exist?
Matthew Vines
cool. How can i read janes age?
people("Jane").Age Which as you can see is a lot easier to work with.
Matthew Vines
@Matthew: No, structs exist to make value types. With all the different properties, the data for a person does not make sense as a single value.
Guffa
But if you look at the DateTime struct. Many properties there, all related to a concept. There are even a few methods in there. Why did they choose to make that a struct when it could just as easily have been a class.
Matthew Vines
Just found this question. http://stackoverflow.com/questions/85553/when-should-i-use-a-struct-instead-of-a-class leads me to believe that this should indeed probably be a class. Thanks for answering my question Guffa.
Matthew Vines
one issue i just hit. 'Person' is not accessible in this context because it is 'Friend'.
The DateTime struct actually only contains an Int64, which holds the data for the Ticks and Kind properties. All other properties are derived from those two.
Guffa
@Mark: Just change Class to Public Class to make it accessible outside the scope where it's declared.
Guffa