Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion - implemented Interface needs casting?

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:

  1. Instantiate collection of Entity Dim entites As New List(Of Entity)
  2. Instantiate WeightsCalculator Dim wc As New WeightsCalculator(...)

Why can I not do wc.Calculate(entities)? I receive:

Unable to cast object of type 'System.Collections.Generic.List1[mynameSpace.Entity]' to type 'System.Collections.Generic.IList1[myNamespace.IWeightable]'.

If Entity implements IWeightable why is this not possible?

like image 693
youwhut Avatar asked Sep 01 '26 07:09

youwhut


1 Answers

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
like image 105
Konrad Rudolph Avatar answered Sep 04 '26 00:09

Konrad Rudolph