views:

605

answers:

2

When I have many controls on a Form (i.e. Label, Button etc) that do almost the same thing, I often use one method to handle all the controls Click, MouseDown, MouseUp events.

But to know which of the controls throwing the event and access the properties of that control I need to cast the "sender" object to the correct type.

The thing is that I always know which type it is, I don't really have to "TryCast", "DirectCast" and check if the operation returns true. I some times use CType as well.

Dim btn as Button = CType(sender, Button)

btn.Txt = "Pushed"

I'd like to find the fastest casting method when I already know the type of the control, I know there is a Button event calling my method and like the fastest way to convert the sender object to a Button control.

Any suggestions?

+6  A: 

I'd use DirectCast as that expresses your intention most clearly: you know the object is actually the right type; you don't need any conversions to be performed, and you don't want them to be performed: if the type is wrong, that indicates a bug and an exception should be thrown, right?

Why are you so worried about performance though? I suspect that DirectCast is at least as fast as the alternatives, but if we're talking about user interactions here the cast is going to be insignificant compared with the human reaction time. Clear code is almost always more important than the absolute fastest way of doing something.

Jon Skeet
Thanks for your thoughts and you are right about that clear code is important :)
Magnus
+2  A: 

Apart from the intent mentioned by Jon, DirectCast will also be the fastest method. More information are in the Hidden Features of VB discussion.

Konrad Rudolph