DISASTERS You Can Avoid With Enum Serialization in CSharp
January 17, 2024
• 638 views
Previously, I've talked about enums in C# and some of the things we can do when structuring our dotnet applications to avoid challenges. When it comes to serialization with csharp enums, we can consider some different pros and cons.
In this video, I walk you through examples of enums in C# and how you can make informed decisions when it comes to serialization.
Have you subscribed to my weekly newsletter yet? A 5-minute read every weekend, right to your inbox, so you can start your weekend lear...
View Transcript
when we're working with enums and C we get something that feels like a string and like an integer and this gets kind of interesting when we think about serialization so when we're trying to save enum data to something and then have ways to restore it or if we're trying to think about how we transfer enum data we need to be able to convert the enum value into something else so that we can send it now the question that we're often faced with is well should we send the string version of the enum or should we send the integer or numeric version of the enum everyone's going to have different opinions about this I think I have my own but instead of just telling you what I think I wanted to be able to walk through some pros and cons of doing different things with serializing
enums if you haven't checked out my first video on enums I'll link it right up here you can go check that out first come right back and hopefully this will continue on in that series and a quick reminder right before I go to visual studio check out that pin comment for my free Weekly Newsletter all right let's jump over to the code in Visual Studio I have an enum called products here and this is an example of an enum that I probably would not recommend that you create so if you watched the first video I talked about enums ideally being something that's not going to change at all or like very often right if you're going to have to change it ideally it's not happening often and if you think about something like products think about me as someone that might want to be creating
products as a content creator if I'm creating products odds are I probably want to be able to expand my product offering over time and if we just have a quick look through this example that we have here you can see that I have my brag document template here I have my design patterns ebook and if I wanted to make more ebooks I would have to go find ways to add these in you can see that I have my Dome train course here and two others that I'm working on right now I also have this free course that I made for introductory to programming but if I want to keep adding more so if I want to do more work with Nick chaps and add more Dome train courses that's going to mean that I have to keep adding things into this and what happens if
I want to disc continue offering products well I'm going to have to remove entries from this product enum so I wanted to frame this up not because this is how I recommend you create a use enums but this is how I see people using it I'm going to create follow-up videos on how I would try to work around this kind of thing but I also wanted to share with you how I think that you can navigate this with respect to serialization if you have something like this in your code base already and it's not trivial for you to get rid of it I think a lot of the time us content creators were trying to teach you like the ideal ways to do things but the reality is if you're already working in a code base that's doing this you're going to have a lot
of work ahead of you to get to that sort of clean state that we're talking about so if you're stuck with an enum like this and you're trying to think about serialization if you're unable to get through all of the refactoring ahead of time this is going to be some stuff that I want you to think about now I mentioned at the beginning of this video that when we're looking at this enum that we have here we could think about this enum in terms of the different values as strings right so this brag document template could be cons like you could look at it like a string version right if we're serializing it or we know that enum values are automatically incremented if we haven't assigned values starting at zero so brag document template is equivalent to the value zero design patterns ebook one so
on and so forth incrementing by one up until intro to programming course so that means when we're serializing we have two obvious ways that we could work with string or numeric representation you could probably come up with other ways too like if you wanted to uh truly serialize this into bytes and you wanted to encode it some way we're talking about another transform on top of that but you're probably looking at a string or numeric representation now I wrote a comment below this enum that has some different ideas that we're going to walk through as a thought exercise and I wanted to do this because I want you to be thinking through this with me as I try to explain my perspective again the goal of this video is not for me to tell you like I absolutely think you have to store and serialize
these as numeric values or you must always use strings for that I have an opinion I want to go through this exercise with you so you can create your own okay let me expand this comment and we'll start going through this list so if we're serializing enums and I mean serializing in the sense of being able to transfer that data whether that's to some other location or into persistent State and then being able to recover it so it's kind of synonymous in this case but if we're trying to serialize enum values I want you to think about what happens if we rename them in the situation where we're talking about these product lists if I want to rename my brag document template and I decided Well in my brag document template I refer to it as a highlight tracker I really don't like calling it
a brag document I just think that some people recognize it is that if one day I decided no thanks we're not going with brag document anymore we are using highlight tracker I want you to think about this if we were serializing our products and every instance that was serialized had brag document written out as a string well what's going to happen now well that enum no longer exists in our code if we were doing some type of parsing to be able to recover that enum from a serialized State we wouldn't easily be able to put it back to a product so we could still do it it's not that it's wrong or it's impossible it's just that we would have to write code at the different locations that are responsible for serializing and deserializing to know that if we have brag document template that now
needs to be converted into highlight tracker template so you end up creating some type of code that has to live on for forever to basically do enum migration now in this particular case if we wrote that out as a numeric value we could effectiv rename the values inside of this enum and the numbers are still going to line up so in this case numeric values would still be helpful for us and we would be able to rename now in either case again if you watch the earlier video when you're changing enums at all a lot of your code base has to be able to update with that so if you're unable to control all of the references to this enum it's going to be a little bit hectic to do a refact or even to rename something because you might have to go update many
projects and maybe different things compiling at different times so it could be a lot more challenging depending on how complex your code is and how widespread the enum use is but let's move on from that example let's talk about reordering things so that's the next thought exercise here if I said well how I'm using my enum I actually want to be able to reorganize this a little bit I want to put my chuses at the beginning so I'm going to move these two right to the end have my chuses first put the Highlight tracker there and then that way uh because maybe I'm done making courses I want to keep adding ebooks and just appending them because that feels good well what's going to happen if we have our enum like this if we had already serialized data so let's say we have a database
we could have a client in a server that are now mismatch inv versions uh and that way they have different versions of the enum on each side like that's this is the exercise I want you to be thinking about um it's a little bit easier I think to think about maybe like a database and trying to to save and load that data so if you save these out to the database before doing the reorder and it was as a string is that going to be an issue at all here well probably not because in this case we're still dealing with the same strings in terms of the enum names they're just in a different order but we didn't care about the order we stored the string but if you were dealing with the numeric value it's kind of the opposite of the first example we
looked at what's going to be happening here is that anything that is a different number has to be remapped you would need to know what sort of version of your enum you're dealing with to be able to do the proper mapping and if you had done both of these things so you had gone through a period of time where you rename things you would have some code that has to know hey that brag document template is now highlight tracker and then later on you go reorder now you have to have that kind of versioning logic built in as well and if you have this kind of stuff in multiple spots which I don't recommend but if you do now you have to update multiple spots to be able to support this we've only gone through two different alterations of this enum and you can see
that it gets pretty complicated pretty fast let's move on to the next so if we want to remove something so one day I decide well I don't want to give away my highlight tracker template anymore I'm over that I'm I'm only going to focus on programming things and not you know software engineering tips so I want to go and delete this right out of here right or maybe I want to get rid of my course that I'm giving away for free this intro to programming course everything is paid for now drop the free courses so I get rid of this if we were dealing with strings what happens now right so we have a database that has some entry in there and it has intro to programming course as a string well if I try to restore that and parse that back to get this
enum value that's not going to work that string no longer maps to an enum value so this is another example where we'd have to write some custom logic to handle that so you need to decide in your business logic what do you do when you have something that existed that doesn't exist anymore more or do you write some code that goes and purges that from your database and handle that separately so that you never run into this encode either way you have to do something to handle this if we were dealing with numeric values it's the same thing in fact it's a little bit worse because not only do we not have that numeric value mapping to intro to programming course we have that numeric value mapping to the next thing right so highlight tracker template now becomes the same value that intro to programming
course was CU everything shifted up by one so again you would need to either go run something across your database to update the enum values or you would need to make sure that you have something in your code that can handle that is sort of a migration so let me undo that one and let's talk about the next one if we're appending something so if we're appending so I say okay it's time for a new ebook what's a good ebook to make well maybe to go along with the course that I have on dome train already I'm going to create refactoring techniques ebook that'll be the new thing that I add right on to the end of this well if we were serializing and storing stuff as the string values there would be nothing that it would have existed with refactoring techniques ebook so we
can go ahead and add this rate to the end of our enum that works pretty well in fact the numeric version is very similar too because we would have had nothing that was set to be that numeric value now that it's at the end right so currently we have 0 1 2 3 4 5 6 so nothing in the database would be refactoring technique ebook as a string or products with the enum value of six so appending things to the end of the enum is kind of nice it seems to work in either case and we have a bit of flexibility there that's something to keep in mind if you're doing this kind of thing now what about inserting so I had mentioned that I wanted to move the ebooks to the end because I was done with courses but now I changed my mind
because Nick chaps approached me and said hey there's another cool Dome train course I want you to do and you got to get recording it so I go okay cool I'm going to do Secret Dome train course 3 I want to group them together right we saw that a pending works really nicely but if I'm being stubborn and I say nope I want to read it in order and that means I have to insert the value into this enum what's going to happen with respect to Strings and integers and serialization well if we were dealing with strings we had nothing that was secret Dome train course 3 so we don't really have a serialization issue if we're trying to read stuff back from the database nothing would have existed like that but again if we had a numeric value we've gone ahead and shifted everything
right so everything that was after secret Dome train course 2 we put secret Dome train course 3 right there everything after that is up by one so we would have to go run some type of migration across the data or build code migration in to be able to handle this different enum version so now our products enum is in this state and this last one that I have is if we want to change the value and I'm not going to necessarily go in depth on this one because this seems to be I would call like more of a rare case that you would do but if you had manually been assigning values to these things instead of moving them around and reordering them you might say like I just want to change all of my choruses to be you know um in the hundred series
all of my ebooks to be in the the 500 Series so you'd have like your ebook starting at 500 the next one at 501 that kind of thing if if you wanted to do that uh and change your mind mid way the same type of thing that we've already seen happens if we're dealing with strings in that case the numeric value changing doesn't really bother us strings have that advantage in that particular case now integer values the numeric value of the enum clearly would break we would have a really complex migration to build into the code or we would have to go change the values in our database to be able to get updated one time and then use our code along with that so as you can see we only compared strings and numeric versions in some simple cases here literally just from changing
the value of the enum the different values that we have inside of it so you can see that it's complex already we have pros and cons to either case strings and integers we haven't even touched about the fact that like strings might take more storage space or you know more btes to transmit uh integers would be less um you have different things to consider completely outs side of what we just talked about so that's why I don't want to prescribe to you that like this is the one way to do it I want you to think about what your current use case is in your code base and take some steps to be able to make it incrementally better so now that we've seen this and if you've gone ahead and watch that first video that I linked at the beginning of this one you'll
know that my ideal state is for us to be able to have enums that are not changing ever but sometimes that's easier said than done and if you can't guarantee that I I want you to be able to think about minimizing the surface area where our enums are used so if you want to see more about how to do that check this video out next thanks and I'll see you next time
Frequently Asked Questions
What are the pros and cons of serializing enums as strings versus integers?
When serializing enums, using strings can make the code more readable and easier to understand, especially when debugging. However, if you rename an enum value, it can lead to issues since the string representation may no longer match. On the other hand, using integers can simplify renaming and reordering enums since the numeric values remain consistent even if the names change. But, if you remove or insert values, you may need to implement complex migration logic to handle the changes.
Why should I avoid using enums for frequently changing data like products?
Enums are best suited for values that don't change often. If you're dealing with products that may frequently be added, removed, or renamed, using enums can lead to complications in serialization and deserialization. It can create a lot of overhead in maintaining the codebase, especially when you need to handle migrations or updates across different parts of your application.
What should I do if I already have enums in my codebase that are frequently changing?
If you're stuck with enums that change often, I recommend minimizing their usage and considering refactoring your codebase to use a more flexible structure, like a database or a configuration file. This way, you can handle changes without the overhead of updating enum values throughout your code. It's about making incremental improvements to reach a cleaner state.
These FAQs were generated by AI from the video transcript.