Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385405

Determine whether a conversion is valid before attempting to perform it

I have the following subroutine:

Private Sub MySub(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ControlEventArgs) Handles Me.ControlAdded
    Try
        AddHandler CType(e.Control, MyDerivedControlType).selectionChanged, AddressOf MyEventHander
    Catch ' This just protects against other types of control being added to the group box
    End Try
End Sub

The intention is that an event handler is set for any control added to the form, but only if it's a certain kind of control — determined by what its most-derived type is.

Putting overarching design concerns aside for the time being, although this subroutine functions properly, when running the debugger the constant exceptions keep leaving messages in my "Immediate Window". It's annoying, and presumably throwing exceptions only to immediately re-catch them is wasteful.

Can I figure out whether the CType will succeed before attempting it? And thus avoid this exception-as-logic-flow?

Upvotes: 2

Views: 344

Answers (3)

Josh
Josh

Reputation: 2975

Before your current line, you could use TryCast instead of the CType. Use the result when adding the event if the result is not nothing.

Upvotes: 1

James Johnson
James Johnson

Reputation: 46077

I don't know what the VB equivalent is, but in C# you can do this:

if (e.Control is MyDerivedControl)
{
    MyDerivedControl ctrl = (MyDerivedControl)e.Control;
}

EDIT: Here's the code in VB.NET

If TypeOf ctrl Is MyDerivedControl Then
    Dim derivedCtrl As MyDerivedControl = DirectCast(ctrl, MyDerivedControl)
End If

Upvotes: 1

ckittel
ckittel

Reputation: 6646

You can make use of TryCast.

Private Sub MySub(ByVal sender As Object, ByVal e As ControlEventArgs) Handles Me.ControlAdded
    Dim ctl = TryCast(e.Control, MyDerivedControlType)
    If (ctl IsNot Nothing) Then
        AddHandler ctl.selectionChanged, AddressOf MyEventHander
    End If
End Sub

TryCast will return Nothing if the cast isn't successful or it will return the object casted to the specified type. I believe in C# this "try cast" would look like var ctl = e.Control as MyDerivedControlType;.

Upvotes: 4

Related Questions