Enums and flags
Many .NET methods take or return a choice from a fixed list — a day of the week, a file attribute, a mode. This lesson shows how enums look in Ring, how to check and parse them, how flags combine, and how to make your own bit flags.
What you will learn#
- what an enum is and how it looks in Ring (a text),
- listing the names, testing a name, parsing a text,
- flags: several choices at once (
ReadOnly, Hidden), - your own flags with the bit operators
&,|and~.
Enums#
An enum is a type with a fixed set of named values: DayOfWeek (Sunday … Saturday), FileAttributes, StringComparison, Environment.SpecialFolder. In C# you write DayOfWeek.Friday; behind the name there is a number. In Ring an enum value is simply the text of its name: you read oDate.DayOfWeek and get "Friday", and when a method wants an enum you pass "Friday". You never need the numbers.
The program#
# enums and flags - named choices from .NET as text, checking and parsing them, and combining options with bits
load "dotnet.ring"
using {
"System"
"System.IO"
}
C_READ = 1 # the options of the permission bits in step 5
C_WRITE = 2
C_RUN = 4
func main
oEnum = new Enum()
oDays = dnType("System.DayOfWeek")
# 1. An enum is a fixed list of names. In Ring an enum value is a TEXT with the name: there is no number to remember.
oDate = new DateTime(2024,5,17)
? "1. 2024-05-17 is a " + oDate.DayOfWeek + ". Is it a Friday? " + yesNo(oDate.DayOfWeek = "Friday")
# 2. All the names of an enum
? nl + "2. the days: " + joinWith(oEnum.GetNames(oDays).toList(),", ")
# 3. Is a text one of the names? Parse turns a text into an enum value, and raises an error if there is no such name.
? nl + "3. is 'Friday' a day? " + yesNo(oEnum.IsDefined([ :enumType = oDays, :value = "Friday" ])) + ". Is 'Funday'? " + yesNo(oEnum.IsDefined([ :enumType = oDays, :value = "Funday" ]))
cDay = oEnum.Parse([ :enumType = oDays, :value = "Friday" ])
? " Parse('Friday') gives " + cDay
try
oEnum.Parse([ :enumType = oDays, :value = "Funday" ])
catch
? " Parse('Funday') raised: " + substr(left(cCatchError,70),nl," ")
done
# 4. A method that takes an enum takes the name as a text: a file can be hidden and read only at the same time
cFile = new Path().Combine([new Path().GetTempPath(),"ringdotnet_enums.txt"])
new File().WriteAllText([ :path = cFile, :contents = "x" ])
? nl + "4. attributes of a new file: " + new File().GetAttributes(cFile)
new File().SetAttributes(cFile,"ReadOnly, Hidden") # several flags: names separated by commas
cAttributes = new File().GetAttributes(cFile)
? " after SetAttributes: " + cAttributes
? " is it hidden? " + yesNo(substr(cAttributes,"Hidden") > 0) + ", is it a directory? " + yesNo(substr(cAttributes,"Directory") > 0)
new File().SetAttributes(cFile,"Normal")
new File().Delete(cFile)
# 5. Your own flags: each option is a power of two, so that every combination is one number. The operators are & | ~
? nl + "5. options as bits:"
nPermissions = C_READ | C_WRITE # read and write
? " permissions = " + nPermissions + " -> " + describe(nPermissions)
nPermissions = nPermissions | C_RUN # add an option
? " after adding run: " + nPermissions + " -> " + describe(nPermissions)
nPermissions = nPermissions & ~C_WRITE # remove an option
? " after removing write: " + nPermissions + " -> " + describe(nPermissions)
? " can it read? " + yesNo((nPermissions & C_READ) != 0) + ", can it write? " + yesNo((nPermissions & C_WRITE) != 0)
func describe nPermissions
aNames = []
if (nPermissions & C_READ) != 0
aNames + "read"
ok
if (nPermissions & C_WRITE) != 0
aNames + "write"
ok
if (nPermissions & C_RUN) != 0
aNames + "run"
ok
if len(aNames) = 0
return "nothing"
ok
return joinWith(aNames," + ")
func joinWith aList, cSeparator
cText = ""
for cItem in aList
if cText != ""
cText += cSeparator
ok
cText += cItem
next
return cText
func yesNo lValue
if lValue
return "yes"
ok
return "no"1. 2024-05-17 is a Friday. Is it a Friday? yes
2. the days: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
3. is 'Friday' a day? yes. Is 'Funday'? no
Parse('Friday') gives Friday
Parse('Funday') raised: DotNet Error: System.ArgumentException: Requested value 'Funday' was n
4. attributes of a new file: Archive
after SetAttributes: ReadOnly, Hidden
is it hidden? yes, is it a directory? no
5. options as bits:
permissions = 3 -> read + write
after adding run: 7 -> read + write + run
after removing write: 5 -> read + run
can it read? yes, can it write? noThis program uses a generic function (dnType) where a class cannot be used. The lesson The generic functions explains them.
How it works#
Comparing#
Step 1 compares the value with a text: oDate.DayOfWeek = "Friday". It reads like English and cannot be confused with another number.
Names, IsDefined and Parse#
Enum.GetNames(type) lists all the names (the tutorial Exploring .NET with reflection explains dnType). IsDefined asks whether a text is a valid name; use IsDefined([ :enumType = type, :value = text ]) (the two-argument form). Enum.Parse checks and converts: a wrong name raises an error that says Requested value 'Funday' was not found. When the text comes from a user or a file, either test it first or try / catch (the tutorial When things go wrong).
Flags#
Some enums are flags: the values can be combined. A file can be ReadOnly and Hidden. In Ring the combination is a text with the names separated by commas: "ReadOnly, Hidden". File.SetAttributes(path, "ReadOnly, Hidden") sets both, and File.GetAttributes(path) returns the same kind of text. To test one flag, look for its name in the text (substr(text, "Hidden") > 0).
Take care with names that contain other names. "Directory" is not part of "ReadOnly, Hidden", but "Read" is part of "ReadOnly". Search for whole names (surround the text with commas and spaces, or split it on commas) when this can happen.
Your own flags with bits#
In your own code you can do the same with numbers. Give each option its own bit: 1, 2, 4, 8, … (powers of two). Then any combination is one number:
| Operation | Ring | Meaning |
|---|---|---|
| combine / add | a | b | the options of both |
| test | (value & C_READ) != 0 | is the bit set? |
| remove | value & ~C_WRITE | clear the bit |
Read and write are 1 | 2 = 3; adding run (4) gives 7; removing write leaves 5. Parentheses are needed around & in a comparison. The same technique stores many yes/no settings in one number, or in one database column.
What you learned#
- enum values are texts in Ring,
GetNames,IsDefined,Parse,- flag enums are comma-separated texts,
- bit flags with
|,&and~.
Exercises#
- Print all the names of
FileAttributes, then read the attributes of a folder withFile.GetAttributesand decide whether it is a directory. - Add a
C_DELETE = 8option and a functionparse("read,write")that turns a text into the number. - Use
StringComparison("OrdinalIgnoreCase") withString.Equalsto compare two texts without regard to case.