0

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

  • 1
    Is there any specific reason you don't want to make a Person class with the different values and put Person objects in a list? – Fredrik Mörk Jun 07 '09 at 19:12

1 Answers1

4

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
  • 687,336
  • 108
  • 737
  • 1,005
  • 1
    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 Jun 07 '09 at 19:35
  • people("Jane").Age Which as you can see is a lot easier to work with. – Matthew Vines Jun 07 '09 at 19:39
  • 1
    @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 Jun 07 '09 at 19:42
  • 1
    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 Jun 07 '09 at 19:46
  • 1
    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 Jun 07 '09 at 19:52
  • one issue i just hit. 'Person' is not accessible in this context because it is 'Friend'. –  Jun 07 '09 at 20:13
  • 2
    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 Jun 07 '09 at 20:14
  • @Mark: Just change Class to Public Class to make it accessible outside the scope where it's declared. – Guffa Jun 07 '09 at 20:16