Visual Basic Constants and Enums

In the previous tutorial on sorting Visual Basic arrays we developed a neat routine to sort the contents of an array.  While the routine works well, it only sorts the array in ascending order.   What would we do if we wanted to allow consumers of the routine to choose what order they wish to sort the array?   This tutorial on Visual Basic Constants and Enums shows you two techniques for doing so, while making your code more readable and maintainable.

Open the Visual Basic Project “Sort Array” and add a new Module to the Project and call it ModuleHelper.

visual basic project add module

Paste these lines of code into the Module:

Public Const ASCENDING As Byte = 0
Public Const DESCENDING As Byte = 1

Cut the Subroutine SortArray from the Form and paste it into this Module under these declarations.

Our aim here is to allow a developer to specify if they want the routine to sort in ascending or descending order using the two constants we have specified.  We can do this a number of ways, but in this context it’s probably easiest to allow the user to pass a parameter to the SortRoutine. This parameter will signal to the routine that the sort should be ascending or descending.

Slightly amend the declaration of the SortArray routine and add this new parameter.

Public Sub SortArray(ByRef array() As Integer, Optional ByVal sortOrder As Byte = ASCENDING)

Firstly, we have made the routine accessible by the Form by making it a Public routine.  In addition, and more relevant to this tutorial, we have added a second parameter, sortOrder, which is a Byte and Optional.    (Note, Byte was chosen as they take up so little memory, 1 byte in fact!  Use the smallest variable types that you can, but never smaller.  Efficiency…)

Examining the second parameter again:

Optional ByVal order As Byte = ASCENDING

Optional instructs Visual Basic that the parameter may be omitted when calling the routine.  This is extremely helpful for us as we have legacy code calling this routine.  Our existing calls to the routine will still be valid as we are passing all the compulsory parameters.  If we don’t pass this parameter the default sort order will be ASCENDING.  It is necessary to specify a default value for all optional parameters so Visual Basic knows how to behave if they are omitted.  This is a great tip to enhancing legacy code, we haven’t broken any existing code at all, yet we’ve enhanced the routine!  In addition, it’s worth noting that optional parameters must be declared at the end of the parameter list.  You can have multiple optional parameters if you wish, but they must be at the end of the parameter list.

Look at these declarations again:

Private Const ASCENDING As Byte = 0
Private Const DESCENDING As Byte = 1

These statements instruct Visual Basic to create a new constant.    Constants are essentially variables which have a constant value.  You can’t change the value of a constant.  Pi is a good example of a constant.  We know the value and it will never change (without catastrophic disruption to the world of maths and physics).  It has a constant value.  In Visual Basic, we can use constants like we use variables – as named values.   Unlike variables, the value of a constant is read only.

We’ll need to modify SortArray Subroutine to sort the array in ascending or descending order based on the new parameter.

Public Sub SortArray(ByRef array() As Integer, Optional ByVal sortOrder As Byte = ASCENDING)

     Dim minimumOrMaximum As Integer
     Dim swapValue As Integer
     Dim upperBound As Integer
     Dim lowerBound As Integer

     lowerBound = LBound(array)
     upperBound = UBound(array)

     For i As Integer = lowerBound To upperBound

          minimumOrMaximum = i

          For j As Integer = i + 1 To upperBound

               'Search for the smallest or largest remaining items in the array
               If array(j) < array(minimumOrMaximum) And sortOrder = ASCENDING Then

                    'The array is to be sorted in ASCENDING order and a smaller value has been found
                    'remember the position of the smaller value in the array
                     minimumOrMaximum = j

               ElseIf array(j) > array(minimumOrMaximum) And sortOrder = DESCENDING Then

                     'The array is to be sorted in DESCENDING order and a larger value has been found
                     'remember the position of the larger item in the array
                     minimumOrMaximum = j

               End If
          Next j

          If minimumOrMaximum <> i Then
               'Swap array Values
               swapValue = array(minimumOrMaximum)
               array(minimumOrMaximum) = array(i)
               array(i) = swapValue
          End If

     Next i

End Sub

The changes are actually quite trivial.

We have an IF statement in the body of the main loop as shown below.

              'Search for the smallest or largest remaining items in the array
               If array(j) < array(minimumOrMaximum) And sortOrder = ASCENDING Then

                    'The array is to be sorted in ASCENDING order and a smaller value has been found
                    'remember the position of the smaller value in the array
                     minimumOrMaximum = j

               ElseIf array(j) > array(minimumOrMaximum) And sortOrder = DESCENDING Then

                     'The array is to be sorted in DESCENDING order and a larger value has been found
                     'remember the position of the larger item in the array
                     minimumOrMaximum = j

               End If

The If Statement merely asks:

  • IF the sort order is ASCENDING and the latest array item is the smallest remember that value (we are sorting from the smallest item to the largest).
  • ELSEIF the sort order is DESCENDING and the item is the largest, remember that value.

The constants ASCENDING and DESCENDING make the code much more readable and memorable.  If I hadn’t used constants here I’d have to write the code instead:

If array(j) < array(minimumOrMaximum) And sortOrder = 1 Then

What does sortOrder = 1 even mean?  Can you imagine a colleague reading your code and seeing that?  The use of the constant DESCENDING makes it much more apparent.   It makes the code easier to read, debug and enhance.

To take that readability (is that even a word?) to the next level paste this code into your ModuleHelper:

Public Enum Order
     Ascending
     Descending
End Enum

I’ll explain what it means in a second; however first go to this line of code in your Form:

Private Sub SortArray(ByRef array() As Integer, Optional ByVal sortOrder As Byte = ASCENDING)

Delete the words “Byte = ASCENDING” and type “Order = Order.”.

What does Visual Basic do?  You should see Visual Basic Intellisense giving you a list of options, either Ascending or Descending.  Select Ascending so your code looks as follows:

Private Sub SortArray(ByRef array() As Integer, Optional ByVal sortOrder As Order = Order.Ascending)

The code responsible for this Intellisense magic is the Enum declaration:

Public Enum Order
     Ascending
     Descending
End Enum

This declaration created something known as an Enumerator.  An Enumerator, or ENum for short, is essentially your own data type.  You have created a data type in Visual Basic, a data type that is made up of two constants; Ascending and Descending.  As an Enum is your own data type, you can declare your own variables of these types e.g.

Dim mySortOrder as Order

Or the Enum it could be the return value of a Function.  An ENum is your own data type!

The body of SortArray code still requires modifying to handle the Enum rather than the constant.

'Search for the smallest or largest remaining items in the array
If array(j) < array(minimumOrMaximum) And sortOrder = Order.Ascending Then

     'The array is to be sorted in ASCENDING order and a smaller value has been found
     'remember the position of the smaller item in the array

          minimumOrMaximum = j

ElseIf array(j) > array(minimumOrMaximum) And sortOrder = Order.Descending Then

'The array is to be sorted in DESCENDING order and a larger value has been found
'remember the position of the larger item in the array

     minimumOrMaximum = j

End If

The calling code in the Form will have to look as follows

SortArray(myArray, Order.Ascending)

Or

SortArray(myArray, Order.Descending)

Or

SortArray(myArray)

The latter option will sort the list in ascending order as that is the default sort order if the Optional parameter isn’t passed.

Change the calling code to sort ascending or descending.  How easy it with Intellisense!  The beauty of Enums is both the readability and of course, Intellisense.  Think of Enums as Constants on steroids.  Good steroids though!

Both Constants and Enums are excellent additions to your Visual Basic arsenal.  Use them wisely and make your code the most readable out there.