Frederic Ribau
Frederic Ribau

Reputation: 1

VB / Issue with CLASS : only last record is showed for all records

I try to get get a list of my songs per album. I have created 2 class : Album & Song, so I can organize them as bellow :

Public Class Album
    Sub New()
        Entered = Now
    End Sub
    Public Entered As DateTime
    Public AlbumName As String = ""
    Public Artist As String = ""
    Public YearReleased As Integer = 1900
    Public Songs As New List(Of Song)
End Class

Public Class Song
    Public SongName As String = ""
    Public SongLength As String = ""
End Class

However, when I ADD songs to album, I always get the last song entered. here is an example with output result.

Protected Sub Test()
    Dim vAlbum As New Album
    Dim vsong As New Song

    vAlbum.AlbumName = "Test 01"
    vAlbum.Artist = "Jackie"
    vAlbum.YearReleased = 2012

    vsong.SongName = "Exit"
    vsong.SongLength = "1.5"
    vAlbum.Songs.Add(vsong)

    vsong.SongName = "Exit II"
    vsong.SongLength = "2.5"
    vAlbum.Songs.Add(vsong)

    For Each sSong As Song In vAlbum.Songs
        Response.Write(sSong.SongName + "<br>")
    Next
End Sub

OUTPUT :

  • Exit II
  • Exit II
  • I have google everywhere but can't find onyl the latest record is showed for all songs.

    Any helps are welcome.

    Thanks, Fred

    Upvotes: 0

    Views: 97

    Answers (2)

    Paul Grimshaw
    Paul Grimshaw

    Reputation: 21034

    Classic Reference problem. Your vsong is always the same object. You need to instantiate a new instance:

    ...
    vAlbum.Songs.Add(vsong)
    vsong = new Song()
    vsong.SongName = "Exit II"
    ...
    

    Upvotes: 2

    sloth
    sloth

    Reputation: 101072

    You're adding the same Song twice, just altering its fields.

    you should use something like this:

    Dim vAlbum As New Album
    
    vAlbum.AlbumName = "Test 01"
    vAlbum.Artist = "Jackie"
    vAlbum.YearReleased = 2012
    
    Dim vsong As New Song
    vsong.SongName = "Exit"
    vsong.SongLength = "1.5"
    vAlbum.Songs.Add(vsong)
    
    vsong As New Song ' create a new instance of Song
    vsong.SongName = "Exit II"
    vsong.SongLength = "2.5"
    vAlbum.Songs.Add(vsong)
    

    or better, use a object initializer or create a constructur that takes all necessary values:

    Public Class Song
    
        Public SongName As String = ""
        Public SongLength As String = ""
    
        Public Sub new(name as String, length as String)
            SongName = name
            SongLength = length
        End Sub
    
    End Class
    
    ...
    
    vAlbum.Songs.Add(new Song("Exit", "1.5"))
    vAlbum.Songs.Add(new Song("Exit II", "2.5"))
    

    Upvotes: 1

    Related Questions