Fastest casting in VB.NET with a known type?

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

But in order to find out which of the controls is throwing the event and accessing the properties of that control, I need to pass the sender object to the correct type.

The fact is that I always know what type it is, I really don't need "TryCast", "DirectCast" and check if the operation will return true. I use CType sometimes.

Dim btn as Button = CType(sender, Button)

btn.Txt = "Pushed"

I would 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 as the fastest way to convert the sender object to a Button control.

Any suggestions?

+1


a source to share


2 answers


I would use DirectCast

it as it most clearly expresses your intent: you know the object is actually the correct type; you don't need any conversions, and you don't want them to be performed: if the type is not correct, it indicates an error and an exception should be thrown, right?



Why are you so concerned about performance? I suspect it DirectCast

's at least as fast as the alternatives, but if we're talking about user interactions here, then the listing would be negligible compared to the human reaction time. Open source is almost always more important than the fastest way to get things done.

+9


a source


Apart from the intention mentioned by John DirectCast

will also be the fastest method. For more information, see the discussion on hidden features of VB .



+3


a source







All Articles