views:

195

answers:

4

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.

A: 

Odd, that really ought to work. Have you tried using CType() or DirectCast to cast it to a Message?

RBarryYoung
+1  A: 

You just need to cast PhoneMessage to its base class Message

Aaron Fischer
+2  A: 

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)
scottman666
I see my folly now. I was creating a List(Of PhoneMessage) and trying to add that list to a List(Of Message) with .AddRange().Now I see the correct approach. Thanks, StackOverflow!
DWRoelands
A: 

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.

Paul Keister
It may be that he has option strict or option explicit turned on.
Aaron Fischer