none
Enum=Integer? question

    Question

  • In my code I have a dictionary declared as Dict1= Dictionary(of Object, TreeNode).  The reason I am using Object is because different types are being loaded in it, including some integer enums.  However, in retrieving a given enum's (say it has integer value 10) treenode, the call Dict1(enum1) is valid, while Dict1(10) gives "key not found" exception. 

    This confuses as it seems most of the time, vb.net treats an enum just like it was an integer.  I always thought basically it was an integer, and the enum name was just window dressing.  But the above implies otherwise.  I know VB also does implicit type conversions which maybe makes things even less clear.   Anywas, I would like an explanation of what is going on.


    Thursday, September 24, 2009 1:53 PM

Answers

  • Okay, fair enough, but when I do have an enum declared as an integer, and I've specified each enum's value like in my above example, why did my code fail to equate the number 10 with the ColorEnum.Blue, if ColorEnum.Blue = 10?  In every other instance in my code I have always treated integers and integer enums exactly the same and interchangeably and never had a problem.
    Because an Enum is a Type and an Integer is a Type and the two Types are not the same (they are mutually exclusive).

    EG:

    Public Class Form1
        Private MyInt32 As Integer = 0
    
        Private Enum Int32Enum As Integer
            ZeroValue = 0
            OneValue = 1
            TwoValue = 2
        End Enum
    
        Private Sub Form1Load(ByVal sender As Object, ByVal e As EventArgs) Handles Mybase.Load
            'Notice how you can define the Enum value by passing an Int32 to it as a SET Argument
            Dim TestInt32vsEnum As Int32Enum = MyInt32
            'This works because MyInt32 is just a parameter - it's not a value assignment
    
            'Notice how you can define an Int32 value by passing an Enum value as a SET Argument
            Dim TestEnumvsInt32 As Int32 = Int32Enum.ZeroValue
            'Again, Int32Enum.ZeroValue is just a parameter that by default returns its Integer Value
    
            'Understand that Type Conversion is only possible because somebody involved in the DotNET Framework development
            'already provided a Conversion Type Method to transform the bit structure of a System.Int32 into the bit structure of any
            'Enum Type, and vice versa... without this existing Type Conversion code in the back end, things don't work out.
    
            'Notice how the Int32.ToString and the Enum.ToString are different values.
            Dim ReportString As String = ""
            ReportString &= "Integer Type: " & MyInt32.GetType.ToString & vbNewLine & _
                            "Integer.ToString: " & MyInt32.ToString & vbNewLine & vbNewLine & _
                            "Enum Type: " & Int32Enum.ZeroValue.GetType.ToString & vbNewLine & _
                            "Enum.ToString: " & Int32Enum.ZeroValue.ToString & vbNewLine & vbNewLine & _
                            "Finally, Convert the Integer Value Type to an Enum Value Type" & vbNewLine & _
                            "Converted Type: " & CType(MyInt32, Int32Enum).GetType.ToString & vbNewLine & _
                            "Converted Value: " & CType(MyInt32, Int32Enum) & vbNewLine & _
                            "Converted.ToString: " & CType(MyInt32, Int32Enum).ToString
            MsgBox(ReportString)
    
            
    
        End Sub
    
    End Class




    It never hurts to try. In a worst case scenario, you'll learn from it.
    • Marked as answer by Tekito Thursday, September 24, 2009 5:52 PM
    Thursday, September 24, 2009 5:44 PM

All replies

  • Hi Tekito,

    Here is a code example, I hope it helps you with a dictionary and an ENUMeration.

    Note: I have added the ENUM items to the dictionary in alphabetical order.
              So the associated value in the dictionary is different to the ENUM value.

    I could have given the items in the dictionary any INTEGER value.


    Regards,

    John

    Option Strict On
    
    Public Class Form1
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
            Call Example()
    
        End Sub
    
        Public Enum ExampleEnumOfColor
            Red
            Orange
            Yellow
            Green
            Blue
            Indigo
            Violet
        End Enum
    
        Dim SomeDictionary As New Dictionary(Of ExampleEnumOfColor, Integer)
    
        Private Sub Example()
    
            'Adding items to the dictionary in alphabetical order.>>
            SomeDictionary.Add(ExampleEnumOfColor.Blue, 100)
            SomeDictionary.Add(ExampleEnumOfColor.Green, 200)
            SomeDictionary.Add(ExampleEnumOfColor.Indigo, 300)
            SomeDictionary.Add(ExampleEnumOfColor.Orange, 400)
            SomeDictionary.Add(ExampleEnumOfColor.Red, 500)
            SomeDictionary.Add(ExampleEnumOfColor.Violet, 600)
            SomeDictionary.Add(ExampleEnumOfColor.Yellow, 700)
    
            Dim MyValue As Integer = SomeDictionary.Item(ExampleEnumOfColor.Red)
    
            MessageBox.Show("Red in the ENUM is at position/value = zero. But in my dictionary it has a value = " & MyValue.ToString)
    
            'You are right that an ENUMeration item or element can be cast to an integer.>>
            Dim MyInteger As Integer = CType(ExampleEnumOfColor.Blue, Integer)
    
            MessageBox.Show(MyInteger.ToString & " for ENUM ExampleEnumOfColor.Blue counting from zero.")
    
        End Sub
    
    End Class


    In the above example you could use the ENUM to indicate position, maybe in a game.

    You could use the DICTIONARY values to get the points in the game, perhaps?

    I guess it would make a fun game as the points are NOT in position order compared to the ENUM,
     but are instead in alphabetical order.

    :-)   ;-)  It would get you thinking alphabetically!!
    Thursday, September 24, 2009 2:27 PM
  • Thanks for the example but I think it is showing a slightly different situation.  My fault for not giving an explicit code description.  Your example involves a dictionary with enum keys and a conversion from enum to int, whereas I have a dictionary of object keys and a conversion(?) from int to enum.  See the example below:

    My question is if enums are really integers, why does it not recognize 10 as the enum blue?  In vb.net, if you pass an integer into a subroutine that takes an enum argument, the integer is automatically converted to the enum without problems.  It seems sometimes they are treated as the same thing and other times they aren't, which confuses me.

     Enum ColorEnum As Integer
                Blue = 10
                Red = 20
            End Enum
            Sub DictionaryTest()
                Dim Dict1 As New Dictionary(Of Object, TreeNode)
    
                Dict1.Add(ColorEnum.Blue, New TreeNode)
                Dict1.Add(ColorEnum.Red, New TreeNode)
    
                Dim TN1 As TreeNode
                TN1 = Dict1(ColorEnum.Blue) '-> works okay
                TN1 = Dict1(10) '-> Key not found Error!
            End Sub
    Thursday, September 24, 2009 2:58 PM
  • Hi again Tekito,

    If the above example is too confusing for you.

    Simply think of a DICTIONARY in terms of a word dictionary where you might "look up" any word to retrieve its meaning.
    In VB.Net you use a dictionary to "look up" an item to retrieve its value.

    Hope that helps?

    Regards,

    John
    Thursday, September 24, 2009 2:59 PM
  • Thanks for the example but I think it is showing a slightly different situation.  My fault for not giving an explicit code description.  Your example involves a dictionary with enum keys and a conversion from enum to int, whereas I have a dictionary of object keys and a conversion(?) from int to enum.  See the example below:

    My question is if enums are really integers, why does it not recognize 10 as the enum blue?  In vb.net, if you pass an integer into a subroutine that takes an enum argument, the integer is automatically converted to the enum without problems.  It seems sometimes they are treated as the same thing and other times they aren't, which confuses me.

     Enum ColorEnum As Integer
    
                Blue = 10
    
                Red = 20
    
            End Enum
    
            Sub DictionaryTest()
    
                Dim Dict1 As New Dictionary(Of Object, TreeNode)
    
    
    
                Dict1.Add(ColorEnum.Blue, New TreeNode)
    
                Dict1.Add(ColorEnum.Red, New TreeNode)
    
    
    
                Dim TN1 As TreeNode
    
                TN1 = Dict1(ColorEnum.Blue) '-> works okay
    
                TN1 = Dict1(10) '-> Key not found Error!
    
            End Sub
    
    




    Hi again Tekito,

    Correction to your code. CType is short for Convert TYPE

    Cast it from an INTEGER to the TYPE ColorEnum.>>

    Option Strict On
    
    Public Class Form1
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
            Call DictionaryTest()
    
        End Sub
    
        Enum ColorEnum As Integer
            Blue = 10
            Red = 20
        End Enum
    
    
        Sub DictionaryTest()
            Dim Dict1 As New Dictionary(Of Object, TreeNode)
    
            Dict1.Add(ColorEnum.Blue, New TreeNode)
            Dict1.Add(ColorEnum.Red, New TreeNode)
    
            Dim TN1 As TreeNode
            TN1 = Dict1(ColorEnum.Blue) '-> works okay
            TN1 = Dict1(CType(10, ColorEnum)) '-> Now works okay. :-)
    
        End Sub
    
    End Class

    Regards,

    John

    I'm currently looking for work in Vb.Net software development. :-)
    Thursday, September 24, 2009 3:07 PM
  • So, in other words, you are saying that an enum is not an integer.  Because if they were equivalent, then I don't understand why a type conversion would even be necessary.  I was under the impression (maybe from VB6?) that Blue really was just the integer value 10; no different than if was an ordinary declared int variable.
    Thursday, September 24, 2009 3:21 PM
  • So, in other words, you are saying that an enum is not an integer.  Because if they were equivalent, then I don't understand why a type conversion would even be necessary.  I was under the impression (maybe from VB6?) that Blue really was just the integer value 10; no different than if was an ordinary declared int variable.


    Each Enum value has a Type, and yes, the default Type for all Enum structures is System.Int32 or Integer.  When it's an Enum, the Integer just has a funky String Value.

    IE:


    Public Enum TestDefault 'Default Integer
            Def1 = 1
            'In this Enum structure, 1 is a 32-bit Integer value and Def1 is its String representation.
            Def2 = 2
            'In this Enum structure, 2 is a 32-bit Integer value and Def2 is its String representation.
    End Enum 'TestDefault


    Enumerations can be explicitly declared as any available numeric Type, including Byte, Integer (System.Int32), Long (System.Int64), SByte, Short (System.Int16), UInteger (System.UInt32), ULong (System.UInt64), or UShort (System.Uint16).  What Type you declare it as depends on how you intend to instantiate it.  For example if you're employing an Enumeration so you can pull a 16-bit Unsigned Integer (2 consecutive bytes) out of a network or filestream and then pass that value directly as an argument to some Function that identifies the Uint16 as an Enum value, you can perform some action depending on which Enum value is matched.



    Public Enum TestByte As Byte
            Byt1 = 1
            'In this Enum structure, 1 is an 8-bit Byte value and Byt1 is its string representation
            Byt2 = 2
            'In this Enum structure, 2 is a 8-bit Byte value and Byt2 is its string representation
    End Enum
    
    
    Public Enum TestUint16 As UShort
            Uint1 = 1
            'In this Enum structure, 1 is a 16-bit Unsigned Integer value and Uint1 is its string representation.
            Uint2 = 2
            'In this Enum structure, 2 is a 16-bit Unsigned Integer value and Uint2 is its string representation.
    End Enum


    It never hurts to try. In a worst case scenario, you'll learn from it.
    Thursday, September 24, 2009 3:39 PM
  • So, in other words, you are saying that an enum is not an integer.  Because if they were equivalent, then I don't understand why a type conversion would even be necessary.  I was under the impression (maybe from VB6?) that Blue really was just the integer value 10; no different than if was an ordinary declared int variable.

    Hi Tekito,

    VB.Net is more fussy than VB6.

    Andrew B. Painter has also shown how you can assign values within an ENUM too.

    Thank you Andrew for reminding us all that you can do that too. :-)


    If you don't the default starting value is zero.

    An ENUM element or item can be converted to an INTEGER if it is the default INTEGER type but
     you can have an ENUM of Byte, Integer, Long, Sbyte, Short, UInteger, ULong or UShort

    Therefore an ENUM is a TYPE that can use whole numbers within the range of those mentioned above.


    Option Strict On
    
    Public Class Form1
    
        Public Enum Example As Long
            Red
            Blue
        End Enum
    
    End Class


    The default is Integer a.k.a. System.Int32 as that is the most commonly used numeric type in VB.Net.

    I hope that answers your main question too. :-)


    Regards,

    John
    Thursday, September 24, 2009 3:45 PM
  • Okay, fair enough, but when I do have an enum declared as an integer, and I've specified each enum's value like in my above example, why did my code fail to equate the number 10 with the ColorEnum.Blue, if ColorEnum.Blue = 10?  In every other instance in my code I have always treated integers and integer enums exactly the same and interchangeably and never had a problem.
    Thursday, September 24, 2009 4:24 PM
  • Hi,

    Here a very interesting page about all kind of binding operations

    https://msmvps.com/blogs/deborahk/archive/2009/07/10/enum-binding-to-the-description-attribute.aspx
    Success
    Cor
    Thursday, September 24, 2009 4:35 PM
  • Okay, fair enough, but when I do have an enum declared as an integer, and I've specified each enum's value like in my above example, why did my code fail to equate the number 10 with the ColorEnum.Blue, if ColorEnum.Blue = 10?  In every other instance in my code I have always treated integers and integer enums exactly the same and interchangeably and never had a problem.
    Because an Enum is a Type and an Integer is a Type and the two Types are not the same (they are mutually exclusive).

    EG:

    Public Class Form1
        Private MyInt32 As Integer = 0
    
        Private Enum Int32Enum As Integer
            ZeroValue = 0
            OneValue = 1
            TwoValue = 2
        End Enum
    
        Private Sub Form1Load(ByVal sender As Object, ByVal e As EventArgs) Handles Mybase.Load
            'Notice how you can define the Enum value by passing an Int32 to it as a SET Argument
            Dim TestInt32vsEnum As Int32Enum = MyInt32
            'This works because MyInt32 is just a parameter - it's not a value assignment
    
            'Notice how you can define an Int32 value by passing an Enum value as a SET Argument
            Dim TestEnumvsInt32 As Int32 = Int32Enum.ZeroValue
            'Again, Int32Enum.ZeroValue is just a parameter that by default returns its Integer Value
    
            'Understand that Type Conversion is only possible because somebody involved in the DotNET Framework development
            'already provided a Conversion Type Method to transform the bit structure of a System.Int32 into the bit structure of any
            'Enum Type, and vice versa... without this existing Type Conversion code in the back end, things don't work out.
    
            'Notice how the Int32.ToString and the Enum.ToString are different values.
            Dim ReportString As String = ""
            ReportString &= "Integer Type: " & MyInt32.GetType.ToString & vbNewLine & _
                            "Integer.ToString: " & MyInt32.ToString & vbNewLine & vbNewLine & _
                            "Enum Type: " & Int32Enum.ZeroValue.GetType.ToString & vbNewLine & _
                            "Enum.ToString: " & Int32Enum.ZeroValue.ToString & vbNewLine & vbNewLine & _
                            "Finally, Convert the Integer Value Type to an Enum Value Type" & vbNewLine & _
                            "Converted Type: " & CType(MyInt32, Int32Enum).GetType.ToString & vbNewLine & _
                            "Converted Value: " & CType(MyInt32, Int32Enum) & vbNewLine & _
                            "Converted.ToString: " & CType(MyInt32, Int32Enum).ToString
            MsgBox(ReportString)
    
            
    
        End Sub
    
    End Class




    It never hurts to try. In a worst case scenario, you'll learn from it.
    • Marked as answer by Tekito Thursday, September 24, 2009 5:52 PM
    Thursday, September 24, 2009 5:44 PM
  • Okay, thanks.  That is what I needed to hear.  Because of this background conversion method, I never realized they were different types.  I had always thought an integer enum was really, truly, just an integer.  Maybe if I put Option Strict On (like JA Oliver's example) it would prevent this background conversion??  That might make it make it clearer to people like me...

    Thursday, September 24, 2009 5:52 PM
  • Option Strict ON is really just a compiler directive that causes the compiler to error and halt when it finds an implicit definition or value assignment.  When Option Strict is ON In Visual Studio (either by declaration in a code file or as a global option in the IDE), the IDE attempts to identify these compiler errors as you write your code, but just like MS Word can't identify all spelling errors, the IDE won't identify all implicit conversions (and in some cases will identify them where they don't exist because it doesn't know something you do).

    Point in fact, as I've said on another thread, programming with Option Strict ON will not make you a better programmer or make your product better either, until or unless you already have a solid and comprehensive grasp of exactly what a Type is, what it represents, and what lies beneath.  It may force you to do a great deal of research on various Types as it tells you "Variable X is not compatible with Variable Y," but even that isn't going to help you significantly until you figure out just what Variable X really is to the computer as opposed to what it is to Visual Basic; presumably you already know what it is to your application.

    Edit to add: Also, with Option Strict ON, you can STILL compare an Int32 Value to an Enum Value of Type Int32 because the Value Type is the default return value on the Enum, and you can STILL set an Enum Value into an Int32 value directly, but you can NOT assign an Int32 value into an Enum Value without Type Casting. So I think, in your case, working with Option Strict ON would have actually created more and more powerful confusion.

    EG:

    Option Strict On
    
    Public Class Form1
        Private MyInt32 As Integer = 0
    
        Private Enum Int32Enum As Integer
            ZeroValue = 0
            OneValue = 1
            TwoValue = 2
        End Enum
    
        Private Sub Form1Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
            'Notice how you can define the Enum value by passing an Int32 to it as a SET Argument
            Dim TestInt32vsEnumUNCAST As Int32Enum = MyInt32 'See how it says this is an error in your IDE?
            Dim TestInt32vsEnum As Int32Enum = CType(MyInt32, Int32Enum)
            'This works because MyInt32 is just a parameter - it's not a value assignment
    
            'Notice how you can define an Int32 value by passing an Enum value as a SET Argument
            Dim TestEnumvsInt32 As Int32 = Int32Enum.ZeroValue
            'Again, Int32Enum.ZeroValue is just a parameter that by default returns its Integer Value
    
            If TestInt32vsEnum = TestEnumvsInt32 Then
                MsgBox("You see that an Int32 value of 0 is comparable (and in this case equal) without type casting to an Int32Enum value of 0; that's because the Int32Enum is of Type Integer; change it to Short and see what happens.")
            End If
    
            'Understand that Type Conversion is only possible because somebody involved in the DotNET Framework development
            'already provided a Conversion Type Method to transform the bit structure of a System.Int32 into the bit structure of any
            'Enum Type, and vice versa... without this existing Type Conversion code in the back end, things don't work out.
    
            'Notice how the Int32.ToString and the Enum.ToString are different values.
            Dim ReportString As String = ""
            ReportString &= "Integer Type: " & MyInt32.GetType.ToString & vbNewLine & _
                            "Integer.ToString: " & MyInt32.ToString & vbNewLine & vbNewLine & _
                            "Enum Type: " & Int32Enum.ZeroValue.GetType.ToString & vbNewLine & _
                            "Enum.ToString: " & Int32Enum.ZeroValue.ToString & vbNewLine & vbNewLine & _
                            "Finally, Convert the Integer Value Type to an Enum Value Type" & vbNewLine & _
                            "Converted Type: " & CType(MyInt32, Int32Enum).GetType.ToString & vbNewLine & _
                            "Converted Value: " & CType(MyInt32, Int32Enum) & vbNewLine & _
                            "Converted.ToString: " & CType(MyInt32, Int32Enum).ToString
            MsgBox(ReportString)
    
        End Sub
    End Class
    It never hurts to try. In a worst case scenario, you'll learn from it.
    Thursday, September 24, 2009 6:17 PM
  • Okay, thanks for the info.  That under-the-hood stuff explains things a bit.
    Thursday, September 24, 2009 6:24 PM
  • I think I may be causing confusion for newbies (and probably oldbies who work with Option Strict On) here.

    I have my Visual Studio IDE set to Option Strict ON by default, but for some reason it behaves a little differently when I include it as a declaration in my code file.  So some of the explanations and assertions I made in these recent posts to this thread have been WRONG.  Those mistakes should be pretty self-apparent to anyone who does have Option Strict ON.

    For some reason, this is ONLY with my Snippets project which is a blank project I use pretty exclusively for writing snippets to post here... if anybody can suggest a reason that it behaves like Option Strict is OFF when it's set ON as an IDE Option in this particular project, it would be much appreciated.
    It never hurts to try. In a worst case scenario, you'll learn from it.
    Thursday, September 24, 2009 7:50 PM