Knowing if a property thats an enum has been set

Interesting question from a dev I’ve know for a long time.

If I have a property that’s an enum, how do I tell that it’s not been set?

And this is a good question.

Because an enum is, at its core, an integer when you declare one and run its always initialized to the default value for an integer – 0.

And so if you use this fact you can actually detect that its been set or cleared.

Simply make you list of enumerated values NOT use 0 as a valid value.

Public Enum myEnum
valueName1 = 1
valueName2 = 2
valueName3 = 3
End Enum

And now any time the value is 0 when your code starts to run you can tell any property that is declared to be a myEnum is or is not set by checking

Private Property someProperty as myEnum

Sub Open() Handles Open
  
  If 0 = Integer(someProperty) Then
    break
    // someProperty has never been set or has been deliberately set to 0
  End If
End Sub

2 Replies to “Knowing if a property thats an enum has been set”

  1. To make that explicit , and analogous to SQL I would declare the enum as:
    Public Enum myEnum
    Null = 0
    valueName1 = 1
    valueName2 = 2
    valueName3 = 3
    End Enum

    1. Certainly a possibility to define the 0 value as something that should be interpreted as “unset”.
      One reason I did not do this is that defining the 0 value makes it perfectly legal to set the value, quite simply, back to “unset” and the code wont look odd.
      With the 0 value NOT used you have to cast 0 to the ENUM type to set it to “not set” which should stand out in your code.

Comments are closed.