MahanGM
MahanGM

Reputation: 2382

Add a structure to a collection in VB.NET

Recently I found that I'm not able to instantiate a structure for an array:

Dim mObjectLists() As New objectLayout

OK, fair, but it's an easy way to store a bunch of data in an array instead of defining a class. And after that, I tried to define this:

Dim mObjectLists() As Collection

And add structures to the collection. But it says you should instantiate the reference object first. I searched about creating my own Collection based on the base collection class, but I think it's wasting ones time to write code with class inheritance instead of the first sample.

What should I do to solve my problem like the first sample :).

Upvotes: 3

Views: 9071

Answers (1)

chrissie1
chrissie1

Reputation: 5029

You may use something like this:

Module Module1

    Sub Main()
        Dim list As IList(Of NewStructure)
        list = New List(Of NewStructure)
        list.Add(New NewStructure() With {.Name = "test1"})
        list.Add(New NewStructure() With {.Name = "test2"})
        Console.WriteLine(list(0).Name)
        Console.WriteLine(list(1).Name)
        Console.ReadLine()
    End Sub

    Public Structure NewStructure
        Property Name As String
    End Structure
End Module

Upvotes: 5

Related Questions