none
Collection Initializers: Pls tell me where I am going wrong RRS feed

  • Question

  • Public Class Galaxy
        Public Property name As String
        Public Property megaLightYears As Double
    End Class
    Module Module1
        Sub Main()
            Dim galaxyone As New List(Of Galaxy)
            galaxyone.Add(New Galaxy("Tadpole", 400))    
        End Sub
    End Module

    As you see from the above pic, I am getting an error under "Tadpole". Would be really nice if someone can point my mistake. I was referring to the following page to learn the collection initializers.

    https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/collection-initializers/index


    Sougata Ghosh

    Sunday, July 8, 2018 11:26 AM

Answers

  • Here are two methods, the one using "with" does not require the sub new with arguments only the second usage does to allow the other one to be valid. If you use the one using "with" discard the second sub new constructor.

    Public Class Galaxy
        Public Property name As String
        Public Property megaLightYears As Double
        Public Sub New()
    
        End Sub
        Sub New(pName As String, pMegaLightYears As Double)
            name = pName
            megaLightYears = pMegaLightYears
        End Sub
    End Class

    Usage 

    Dim galaxyone As New List(Of Galaxy)
    galaxyone.Add(New Galaxy() With {.megaLightYears = 400, .name = "Some name"})
    galaxyone.Add(New Galaxy("another name", 300))
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Marked as answer by sougata12 Sunday, July 8, 2018 11:38 AM
    Sunday, July 8, 2018 11:33 AM
    Moderator