logo VB.Net - Write Binary File
Guide Contents
DigitalDan Home Page

Enum
It is sometimes necessary to place a restriction on a variable and enforce a rule that it can only hold fixed values. Anything in the allowed list is permitted but the variable must not accept any other value. With boolean variables, you can set the variable to True or False, nothing else is allowed.
 
What happens when you want to decide what values are allowed? In the examples below, a shop sells jugs, cups and saucers. They never sell any other crockery.
As a programmer, you want to enforce a program rule - any variable linked to Crockery will only accept the value Jug, Cup or Saucer.
 
The first step is to create our own variable-type and include a list of every "allowed" value. Fortunately, the keyword Enum makes this easy.
 
Private Enum Crockery
Jug
Cup
Saucer
End Enum

 
Here is an example of a function reading the value of a Crockery variable
 
Private Shared Function Crockery_To_String(crock1 As Crockery) As String
If crock1 = Crockery.Jug Then Return "Jug"
If crock1 = Crockery.Cup Then Return "Cup"
' crock1 can only be set to Cup or Jug or Saucer
' It is not Jug and it is not Cup
' therefore it must be Saucer
Return "Saucer"
End Function

 
In this example, we will assign a value to a Crockery variable
 
Private Shared Function String_To_Crockery(s As String) As Crockery
If s = "Jug" Then Return Crockery.Jug
If s = "Cup" Then Return Crockery.Cup
' Crockery can only be set to Jug or Cup Or Saucer
' It is not Jug and it is not Cup
' therefore it must be Saucer
Return Crockery.Saucer
End Function

DigitalDan.co.uk ... Hits = 127