tags:

views:

63

answers:

1

I posted a similar question before, which worked in C# (thanks to the community), but the actual problem was in VB.Net ( with option strict on). Problem is that tests are not passing.

Public Interface IEntity
    Property Id() As Integer
End Interface

    Public Class Container
    Implements IEntity
    Private _name As String
    Private _id As Integer
    Public Property Id() As Integer Implements IEntity.Id
        Get
            Return _id
        End Get
        Set(ByVal value As Integer)
            _id = value
        End Set
     End Property

    Public Property Name() As String
        Get
            Return _name
        End Get
        Set(ByVal value As String)
            _name = value
        End Set
    End Property
End Class

Public Class Command
    Public Sub ApplyCommand(ByRef entity As IEntity)
        Dim innerEntity As New Container With {.Name = "CommandContainer", .Id = 20}
        entity = innerEntity
    End Sub
End Class

<TestFixture()> _
Public Class DirectCastTest
   <Test()> _
    Public Sub Loosing_Value_On_DirectCast()
        Dim entity As New Container With {.Name = "Container", .Id = 0}
        Dim cmd As New Command
        cmd.ApplyCommand(DirectCast(entity, IEntity))
        Assert.AreEqual(entity.Id, 20)
        Assert.AreEqual(entity.Name, "CommandContainer")
    End Sub
End Class
+4  A: 

The same is true in VB as in C#. By using the DirectCast, you're effectively creating a temporary local variable, which is then being passed by reference. That's an entirely separate local variable from the entity local variable.

This should work:

Public Sub Losing_Value_On_DirectCast()
    Dim entity As New Container With {.Name = "Container", .Id = 0}
    Dim cmd As New Command
    Dim tmp As IEntity = entity
    cmd.ApplyCommand(tmp)
    entity = DirectCast(tmp, Container)
    Assert.AreEqual(entity.Id, 20)
    Assert.AreEqual(entity.Name, "CommandContainer")
End Sub

Of course it would be simpler just to make the function return the new entity as its return value...

Jon Skeet
Wow, I learned something new today...
Walter