Reputation: 4940
Assuming a base type of "Message"...
Public Class Message
Public ID As Int64
Public Text As String
Public MessageType as String
End Class
...and then two derived classes...
Public Class PhoneMessage
Inherits Message
Public MessageLength As Int64
End Class
Public Class MailMessage
Inherits Message
Public Postage As Int64
End Class
I would like to have one collection of Message objects which can be either PhoneMessages or MailMessages, so that I can iterate through the list and deal with each message based on what type it happens to be.
Attempting just to use .Add() fails, saying that I can't add an item of type PhoneMessage to a List(Of Message). Is there some elegant way to accomplish what I'm trying to do? I had thought I could accomplish this with generics, but I think there's a gap in my understanding. If it can be accomplished in .NET 2.0, that would be ideal.
Thank you in advance.
Upvotes: 1
Views: 7962
Reputation: 13097
Here's some code that proves that scottman666 is correct:
Public Class InheritanceTest
Public Class Message
Public ID As Int64
Public Text As String
Public MessageType As String
End Class
Public Class PhoneMessage
Inherits Message
Public MessageLength As Int64
End Class
Public Class MailMessage
Inherits Message
Public Postage As Int64
End Class
Public Shared Sub ListTest()
Dim lst As New List(Of Message)
Dim msg As Message
msg = New PhoneMessage()
lst.Add(msg)
lst.Add(New MailMessage())
End Sub
End Class
I would recommend that you consider using Overidable and MustOveride functions to make polymorphic objects. There is a good way to handle the design pattern your working with.
Upvotes: 0
Reputation: 746
The way you describe how you are adding the items to the list should work. Perhaps there is something missing from your code? With the code you gave for your classes, this should do the trick:
Dim phoneMessage As New PhoneMessage()
Dim mailMessage As New MailMessage()
Dim messageList As New List(Of Message)()
messageList.Add(phoneMessage)
messageList.Add(mailMessage)
Upvotes: 2
Reputation: 21231
You just need to cast PhoneMessage to its base class Message
Upvotes: 1
Reputation: 56755
Odd, that really ought to work. Have you tried using CType() or DirectCast to cast it to a Message?
Upvotes: 0