How do I create an enum with string integers in PowerShell?
Asked by
~1 more guess
I'm working with some code generated automatically through the openapi-generator-cli, but I'm hitting a snag with an enum definition. PowerShell seems to throw an error since it doesn't accept integers as enum labels. I'm trying to figure out how to create an enum that uses string representations of integers instead. For instance, I have the enum defined as follows:
enum SerialInterfaceV130BitRate {
# enum value: "1200"
1200
# enum value: "2400"
2400
# enum value: "4800"
4800
# enum value: "9600"
9600
# enum value: "19200"
19200
# enum value: "38400"
38400
# enum value: "57600"
57600
# enum value: "115200"
115200
# enum value: "230400"
230400
}
I get a ParserError that indicates a missing closing '}' in the statement. I've also tried changing the format to '1200' or '1200'=1200, but those didn't work either. What am I missing?
Answers
I think the issue lies in naming conventionsโenum identifiers can't start with numbers, similar to variable naming rules in C#. You might want to rethink how you're defining them.
Reply to this answer
It's crucial to remember that enum labels in .NET must adhere to naming conventions, meaning they can't be purely numeric. If you're looking for a collection of values, you might want to consider using an array instead. For stricter typing, using a `HashSet` could be a good alternative!
Reply to this answer
You should use .value__ to access the integer of an enum. For example:
```powershell
enum SerialInterfaceV130BitRate {
V1200 = 1200
V2400 = 2400
V4800 = 4800
V9600 = 9600
V19200 = 19200
V38400 = 38400
V57600 = 57600
V115200 = 115200
V230400 = 230400
}
$ByName = [SerialInterfaceV130BitRate]::V230400
$ByInt32 = [SerialInterfaceV130BitRate] 230400
$AsInt = ([SerialInterfaceV130BitRate] 230400).value__
```
This way, you can work around the issue and play with the values as needed!
_general_admission: In theory, you could try using ```powershell [SerialInterfaceV130BitRate] 1200 -eq 1200 ``` That should return true without needing to convert it to an integer.
Reply to this answer
Could you explain how you're trying to use the enum? You have the option to either set the number as the value directly or cast the enum to an integer. Although, editing might not help if the enum's design is incorrect.
~1 more guess: I tried to adapt the suggestions but keep running into the same parser error. Hereโs what I modified: ```powershell enum SerialInterfaceV130BitRate { '1200' '2400' '4800' '9600' '19200' '38400' '57600' '115200' '230400' } ``` Nothing seems to fix the missing closing bracket issue!
Reply to this answer
Add your answer
Answers are reviewed before publication.
_exit_stage_left: That makes sense! Iโll brainstorm a workaround for the identifiers.