Option Strict On does not cause compilation error

  • Thread starter Thread starter Justin
  • Start date Start date
J

Justin

I have set Option Strict On
I also have Enum AssemblyLineStatus As Integer
My question is how come there is no compilation error when I compile
following code?

If CInt(ddlStatus.SelectedItem.Value) = AssemblyLineStatus.Client Then
' do whatever
End If

Shouldn't this cause a compilation error? I know in C#, you have to
explicitly either convert enumation to int or int to enumuation.

Just curious.
Thanks
 
Justin said:
I have set Option Strict On
I also have Enum AssemblyLineStatus As Integer
My question is how come there is no compilation error when I compile
following code?

If CInt(ddlStatus.SelectedItem.Value) = AssemblyLineStatus.Client Then
' do whatever
End If

Shouldn't this cause a compilation error? I know in C#, you have to
explicitly either convert enumation to int or int to enumuation.

VB is different, and less strict here. In VB, **a widening conversion
(essentially, one guaranteed not to lose information) can always occur
implicitly**. Conversion from an enum value to the enum's underlying
type is obviously widening, so in the above code,
AssemblyLineStatus.Client gets widened to its Integer value.

In C#, on the other hand, there is no such general rule of implicitness
for widening conversions, and the set of implicit conversions is hence
much smaller. All conversions between enum types and numeric types -
even an enum's underlying type - must be explicit.

VB.NET is stricter than VB6, but it still isn't as strict as C#.
 
Justin said:
I have set Option Strict On

Good Start ...
I also have Enum AssemblyLineStatus As Integer ....
If CInt(ddlStatus.SelectedItem.Value) = AssemblyLineStatus.Client Then
' do whatever
End If

Shouldn't this cause a compilation error?

CInt() returns an Integer and all Enums are defined as Integer.
I suspect VB sees Enum-to-Integer as a Widening Conversion, much like
Short-to-Integer.
I know in C#, you have to explicitly either convert

If you want to do the comparsion "as" the Enumeration, try this

' Throws ArgumentException (IIRC) for invalid values
Dim eValue as AssemblyLineStatus _
= CType(ddlStatus.SelectedItem.Value _
, AssemblyLineStatus)

If eValue = AssemblyLineStatus.Client Then
' do whatever
End If

HTH,
Phill W.
 
Back
Top