In this episode, we're diving into backed enums and how they're actually a lot more useful than pure enums when it comes to things like storing values directly in a database.
We kick off by taking our existing example and modifying our enum cases so that each one has an explicit value, just like we did with constants earlier in the course. The video walks you through a little "gotcha"—if you assign a value to an enum case you have to explicitly define the type that enum is "backed" by (either int
or string
). The editor will actually throw errors if you forget to do this, so you'll see exactly what goes wrong and how to fix it.
You'll see that with backed enums, all the values have to be the same type—either integers or strings, but not both. So, you can't mix and match in one enum.
From there, I show you how to access the actual value for each enum case (super important if you're persisting these values in your database!), and how you can use these values just like you would any string or integer elsewhere in your code.
We end off by quickly showing how to bundle up attributes from your enum when saving things like a book's status, and how convenient it is to have these all defined in a single place. This sets us up nicely for the next episode, where we'll get into serialization and deserialization with enums.
So by the end of this one, you'll know how and why to use backed enums, and how to wrangle the values out of them for saving in your database!