Matthew Goulart Matthew Goulart - 1 month ago 11
Vb.net Question

How do I cast an object without re-assigning it to another variable in VB.NET?

I have the following code (

PointLine
and
CalculatedLine
both inherit
Line
):

For Each line As Lines.Line In lines

''Since both Point and Calculated lines are stored in the same list in the XML files,
''we need to force them back to their original type before using them
Select Case line.GetType()

Case GetType(Lines.PointLine)
line = DirectCast(line, Lines.PointLine)
line.init()''ERROR:'init' is not a member of 'PerformanceValidation.EngineValidation.Limits.Components.Lines.Line'

myLimitSeries.Add(line.series)

Case GetType(Lines.CalculatedLine)
line = DirectCast(line, Lines.CalculatedLine)
line.init(dataTable)''ERROR:'init' is not a member of 'PerformanceValidation.EngineValidation.Limits.Components.Lines.Line'
myLimitSeries.Add(line.series)
End Select
Next


The editor complains about
line
not being of type
PointLine
/
CalculatedLine
when i call
line.init()
.

It's important that the original object be casted to either PointLine or CalculatedLine because I "initialize" them to contain calculated information that will be used later on. So basically, I don't want to create a new variable of type PointLine or CalculatedLine to act as a container for the casted Line.

I tried creating a new line of the appropriate type (exactly as I said I didn't want to above) and deleting the original line and adding the new one to the list but of course, it complains about the underlying list being modified.

Is there a way I can treat a
Line
as either a
PointLine
or
CalculatedLine
temporarily without affecting the list?

Thanks!

Answer

You don't need to create a new instance but you need to have a second variable of the right type for the reference. I don't understand when you say "delete", when you cast, you don't delete the instance since both variable are pointing at the same instance.

For Each line As Lines.Line In lines

    Select Case line.GetType()

    Case GetType(Lines.PointLine)
        Dim linePoint As Lines.PointLine = DirectCast(line, Lines.PointLine)

        linePoint.init()
        myLimitSeries.Add(line.series)

    Case GetType(Lines.CalculatedLine)
        Dim lineCalculated As Lines.CalculatedLine = DirectCast(line, Lines.CalculatedLine)

        lineCalculated.init(dataTable)
        myLimitSeries.Add(line.series)
    End Select
Next

No new instance are created here.

If you only call one function, you could always do.

For Each line As Lines.Line In lines

    Select Case line.GetType()

    Case GetType(Lines.PointLine)
        DirectCast(line, Lines.PointLine).init()
        myLimitSeries.Add(line.series)

    Case GetType(Lines.CalculatedLine)
        DirectCast(line, Lines.CalculatedLine).init(dataTable)
        myLimitSeries.Add(line.series)
    End Select
Next
Comments