tags:

views:

212

answers:

3

Hi, I would like to ask humbly to those vb.net experts out there regarding optimization of the code. My example here is

a.

Dim lblEventCategory = CType(Me.gvSpecialEvent.Rows(e.NewEditIndex).FindControl("lblEventCategory"), Label)

b.

 Dim lblEventCategory As Label = CType(Me.gvSpecialEvent.Rows(e.NewEditIndex).FindControl("lblEventCategory"), Label)

Which of the two is more efficient is it letter A? or letter B?

Can somebody help me understand these codes?

Thanks in advance

A: 

The first one defines the variable lblEventCategory as a Variant type. This is generally worse than the second where you use an explicit type. The Variant type is a kind of "catch all" that can safely hold any type of variable, but you lose any and all type safety and warnings that the compiler might have been able to give you. Also a Variant type uses more memory and will be slower at run time because of the conversions that need to be performed on it.

Additionally, method calls will be "late bound" - this means that the calls to those methods will not be resolved until runtime, when the type of the variable is known, the call is then made by name. This is typically astronomically slower than if you use the explicit type where the call can be made "early bound" (i.e., at compile time).

On the other hand, Variant types do have their place. They are useful in OLE automation (COM) programming, if you are interacting with a language like VBScript that only supports variant types. In that situation, you may be wise to wrap the calls into the late-bound code so that the Variant type is converted to and from the correct type at the boundary of the call.

1800 INFORMATION
Incorrect. Before vb2008 the first is defined as an Object type, not a variant. In vb2008 (assuming Option Infer On) is defined as a label.
ggf31416
There is no such thing as a variant type in VB.NET.
Meta-Knight
+4  A: 

if we are talking .Net 3.5 than what 1800 INFORMATION says is not true since type inference will take place and the compiler will infer the type and hence be typesafe. so in .Net 3.5 a and B are the same.

In Visual studio 2008 just turn Option Infer On or Off to see the difference.

Before .Net 3.5 no type inference will take place and it will use the variant type or rather the object type. So in pre.Net 3.5 A and B are not the same.

chrissie1
In vb2008 Type inference is a language feature, independent of the version of the framework. if .net 2.0 is targeted the type inference won't change.
ggf31416
+2  A: 

In .NET 3.5 Dim x = value is the same as C# var x = value; The compiler will infer the type so both are equal at runtime.

eWolf
See ggf31416 comment to chrissie1's answer. Type inference works in Visual Studio 2008 regardless of the framework version (yes, it works even if you are targeting .Net 2.0).
chyne