Enums are useful because they help you avoid magic numbers. You can write your code in a way that is easy to read and understand from the human’s perspective, which, at the end of the day, is pretty important.
Exposing enums on your Web API
I want to share my enums with other things, notably my Angular front end. As far as the computer is concerned, they are just numbers; but that’s not all that useful if you want to create a user interface. It would really be nice to have a key/value pair of the number and the label, synced up with the enum itself.
Here we’re getting all of the values for the specified enum type, casting them to the appropriate type (in this case, we have an enum of integers), and returning the name of each value and the value itself.
This private function allows us then to quickly expose whichever enum values we want over web API.
Javascript–Caching a web request with Promises – Darchuk.NET
[…] so we really only need to fetch it once, and then store the result for easy access (maybe its an Enum that you map to a list of key/value pairs). We can do this easily enough in a service, but if two calls are made to the service in […]
.NET Core 3.0 Upgrade–New JSON Serializer Gotchas – Darchuk.NET
[…] had my enum controller which provided a key/value pair representation of a C# enum for my javascript client…, but it was returning a C# 7 tuple, which doesn’t properly map with the new JSON […]