I have an Entity class which Implements IWeightable:
Public Interface IWeightable
Property WeightState As WeightState
End Interface
I have a WeightCalculator class:
Public Class WeightsCalculator
Public Sub New(...)
...
End Sub
Public Sub Calculate(ByVal entites As IList(Of IWeightable))
...
End Sub
End Class
Following the process:
Dim entites As New List(Of Entity)Dim
wc As New WeightsCalculator(...)Why can I not do wc.Calculate(entities)? I receive:
Unable to cast object of type 'System.Collections.Generic.List
1[mynameSpace.Entity]' to type 'System.Collections.Generic.IList1[myNamespace.IWeightable]'.
If Entity implements IWeightable why is this not possible?
This doesn’t work.
Assume you have a different class, OtherEntity, that would also implement the interface. If your above code would work, the method Calculate could add an instance of OtherEntity to your list of Entity:
Dim entities As New List(Of Entity)()
Dim weightables As List(Of IWeightable) = entities ' VB forbids this assignment!
weightables.Add(New OtherEntity())
That is illegal. If it weren’t, what would the content of entities(0) be?
To make the code work, use a generic method with a constraint instead:
Public Sub Calculate(Of T As IWeightable)(ByVal entites As IList(Of T))
...
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With