How to change from a string input to an enum input using an an Angular app sending to a C# API

Posted by:

|

On:

|

Lets say you have a class that needs to use an enum, for instance in dungeons and dragons, you have a monster class that is going to have an alignment. Defining the enum is simple enough, define the enum

Now, change where you were previously using a string input to an alignment input

Change the corresponding methods

Manage necessary changes in your data. In my case, I will be dealing with spaces in my input for things like “Chaotic Neutral”. Enums do not work well with spaces, so the first thing I do was remove any whitespace and internal spaces with replace and trim. Then, I use a bool to check I can successfully parse an equivalent enum from the input. This is CASE sensitive. I am not concerned with that though, as I plan to eventually add a drop down list so to limit options to the 9.

It works!

Enums are fairly narrow in scope, but it’s still good practice to use them where applicable.