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?
You can make use of TryCast.
TryCastwill returnNothingif 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 likevar ctl = e.Control as MyDerivedControlType;.