elroyskimms
Member
- Joined
- Jul 10, 2015
- Messages
- 19
- Programming Experience
- 10+
Sometimes I just can't wrap my head around Generics...
For the sake of simplicity, I've boiled everything down to a very simple example that you can copy and paste. I have a generic interface which is restricted to types that implement IComparable. I have a Class that Implements this interface. I create 3 different kinds of this Class using different Types that each implement IComparable (Integer, Long, and Decimal). I create a generic List to contain these 3 items and that's where I get the InvalidCastException. How can I create a List of items that all implement the same interface (and/or inherit from the same class)?
The real code has a variety of methods and properties which require IComparable, but I've removed those just to keep this example short.
It's probably something simple, but my head hurts and I can't figure it out. Thank you for any suggestions you might have,
-E
For the sake of simplicity, I've boiled everything down to a very simple example that you can copy and paste. I have a generic interface which is restricted to types that implement IComparable. I have a Class that Implements this interface. I create 3 different kinds of this Class using different Types that each implement IComparable (Integer, Long, and Decimal). I create a generic List to contain these 3 items and that's where I get the InvalidCastException. How can I create a List of items that all implement the same interface (and/or inherit from the same class)?
VB.NET:
Public Class SampleImplementation
Public Sub RunMe()
Dim Item1 As New Sample(Of Long) With {.Value = 424242, .strName = "Hello-Long"}
Dim Item2 As New Sample(Of Integer) With {.Value = 42, .strName = "Hello-Integer"}
Dim Item3 As New Sample(Of Decimal) With {.Value = 42.42, .strName = "Hello-Decimal"}
Dim List1 As New List(Of interfaceSample(Of IComparable))
List1.Add(Item1)
List1.Add(Item2)
List1.Add(Item3)
End Sub
End Class
Public Interface interfaceSample(Of T As IComparable)
Property Value As T
Property strName As String
End Interface
Public Class Sample(Of T As IComparable)
Implements interfaceSample(Of T)
Public Property strName As String Implements interfaceSample(Of T).strName
Public Property Value As T Implements interfaceSample(Of T).Value
End Class
The real code has a variety of methods and properties which require IComparable, but I've removed those just to keep this example short.
It's probably something simple, but my head hurts and I can't figure it out. Thank you for any suggestions you might have,
-E