Last post Nov 09, 2009 05:42 AM by Boddam
Nov 08, 2009 05:42 PM|Boddam|LINK
I've tried to make sense of these. And im down to directcast vs. trycast in most cases. My question is directcast vs. trycast when bringing in Controls like a label from a formview to change the text: DirectCast(Formview1.FindControl("Label1"), label).Text
= "abc". Shall prefer TryCast over DirectCast in such situations? Both works but is there any "performance gain" or something else?
Nov 08, 2009 08:45 PM|mbanavige|LINK
The difference between a DirectCast and a TryCast is that TryCast will return Nothing if the cast cant be performed while a DirectCast will throw an exception if the cast cant be performed.
TryCast can be used where the cast may fail to avoid the performance penalty associated with throwing an exception. But, you need to check the return from the TryCast to see if it is Nothing before you can safely work with it.
In you example above, I would just use a DirectCast as the TryCast doesn't benefit you. If for any reason, you cannot cast the control you found to a Label control, then DirectCast will throw an exception. TryCast will not throw an exception, but it will
return Nothing and as soon as you try to use the Text property of Nothing, you'll get an object reference exception.
If you wanted to code the cast a little more defensively you could do something like this:
Dim lbl As Label = TryCast(Formview1.FindControl("Label1"), Label)
If Not lbl Is Nothing Then
lbl.Text = "abc"
In this case, by incorporating the TryCast, if FindControl fails to find the label control, or finds something that is not a label control, no exception will be thrown and the lbl object will simply be Nothing.
From a performance perspective, i would think TryCast has just a little more going on under the hood than DirectCast in order to prevent the exceptions but i suspect that the performance differences are extremely minimal.
Nov 09, 2009 05:42 AM|Boddam|LINK
I appreciate that elaborated answer, thanks!