I would like to be able to pass a string into a method and have that method decide which kind of object to return. For example, I would like to pass the "woof" string into a method like the one illustrated below and have it return a "dog" object. Is such a thing possible
I know that I can set the function return type to "Animal" since all three objects are derived from animal, but if I do that I will lose functionality in the "Parrot" object which inherits first from "Animal" then from "Bird". For example, I would lose the ability to write "a.Wings" to the console (illustrated below) because the base class "Animal" does not have the ".Wings" property which resides in the more specific "Bird" class.
Another option would be to set the function return type to "Object". This seems like a far from elegant solution. Isn't there something more interesting I could do with Generics or some other cool new feature of VB 2005
Function GetObject(ByVal speak As String) As Animal 'or Object Select Case speak Case "woof" 'Inherits Animal Dim d As New dog d.color = brown d.legs = 4 Return d Case "meow" 'Inherits Animal Dim c As New cat c.color = black c.legs = 4 Return c Case "polly wants a cracker" 'Inherits Animal ==> Bird Dim p As New parrot p.color = brown p.legs = 2 p.wings = 2 Return p End Select End Function |
Sub WriteToConsole(ByVal a As Animal) Dim writeString As String writeString = "Color: " & a.Color & ", " & "Legs: " & a.legs 'can't write a.Wings to console from animal object 'since this property is inherited from the bird class Console.WriteLine(writeString) End Sub |

fun with oop
dbsize
Knagis
jacco2
remember, ToString is a virtual method of object. override it for all your classes.
Matthew Weyland
The point is. . .
this is not OOP:
Sub WriteToConsole(ByVal a As Animal)
End Sub
Your class should know how to write itself via Animal.ToString() or Animal.WriteToConsole()
I suggest you run the code I posted.