How To Convert Strings To Enums in C#
November 3, 2023
• 1,894 views
In our previous video, we looked at the basics of Enums in C#. We saw that we could cast integers to the Enum type, but we couldn't do that with strings. So how can we go from a string to an Enum type? Let's find out in this C# tutorial on Enums!
Have you subscribed to my weekly newsletter yet? A 5-minute read every weekend, right to your inbox, so you can start your weekend learning off strong:
https://subscribe.devleader.ca
Check out more Dev Leader content (including full in-depth articles...
View Transcript
when it comes to enums and different programming languages we seem to have the ability as programmers to be able to access something that looks like both a string and an integer at the same time and depending on the context that you're using it you get either that numeric value or that string representation so enums can be really handy for us as programmers because it can make our code a lot more readable if you watch my previous video on enums we looked at some of the basics of how we can Define them and how their values are initialized so if you haven't checked that out yet you can go ahead and watch that right here and then come right back to this one to look at some additional examples what we observed in the last video is that we can cast an integer value to the
enum type but we can't cast a string to the enum type and that's a little bit weird because the enum seems to represent both a string and an integer so why does one work but the other doesn't and what can we do about that so in this video we're going to look at how we can take a string and go to that enum value to be able to work with that encode and before I jump over to visual ual studio just a quick reminder to subscribe to My Weekly Newsletter it's totally free and every week you'll get software engineering topics as well as net focused articles I try to include exclusive early access to YouTube videos so you can check these out before the release to the public as well as some dedicated articles that only newsletter subscribers see you'll get a Content recap for
the week as well as some things like programming exercises and little tidbits for you to play with so check that out I'll have a link for it in the comments below and with that said let's jump over to visual studio and see how we can go from strings to enum values very easily all right so the enum type that we're going to be working with is the same from the last video I've just created a day of the week enum and we have the values Monday through Sunday declared for this enum type and like I said in the intro to this video what we observed is that we cannot take a string and cast it to be this enum type so if we had the string Monday we could not just put in front of it parentheses with day of the week and do c
casting to get a variable assigned to this enum type and that's a little bit unfortunate because it does work with the numeric type but not with strings so what can we do instead all right so the examples we're going to be looking through are this enum static class that we have to work with and the tri parse methods that are available there I wanted to call out for this video I'm only going to be looking at Tri parse but there are normal parse variations instead and this is a common practice with some of the net types where the is a parse or some other method and then a try variation and the difference between these implementations is that in the normal variation which is just parse if it fails it will throw an exception but the signature of the method is changed such that the
return type is the day of the week if it succeeds and like I mentioned if it fails it will throw an exception the tri parse variation we're going to be looking at behaves the same way but the structure of the method calls a little bit different so instead of throwing exceptions which will be a little bit more convenient for us in this video what we're going to have is a true or false return type so I'm going to be assigning that in this first example to did parse one and then the output parameter is actually on the method signature itself so we get triy parse one being output and if it's successful we'll get an enum value in there if it fails it will be the default value of the enum so I just want wanted to call out that we're not looking at parse
but it will behave the exact same way it's just that parse will throw exceptions when something does not work and tri parse simply has a false instead of true when something does not parse properly so the first example that we're going to look at is try parse with a single input parameter which is just the day of the week that we want to parse and then an output parameter which is what the result will be if it succeeds now there are a couple of other flavors of this and we're going to see those in examp example 2 and three here what we have is this ability to ignore the case or not so if we wanted to ensure that we're only dealing with case sensitive parsing we can toggle this to be true or false depending on what we need and just to illustrate that
I'm going to show you the two different flavors where it is true and when it is false for whether or not we should ignore the case so you can see on this example here I have Tuesday and it's all lowercase and then I'm saying that we should ignore the case when we go to pars it so I suspect that when we go to run this Tuesday all lower case will work properly similarly when we're saying that we should not ignore the case and Friday is the proper casing that we'd expect this should also parse successfully but what about example one up here the default where there is no ignore case specified what's the default behavior of this API if we try to parse and it's all lowercase and we have not been able to indicate ignore case or not let's run this and find out
all right so here is the output from our program and we have some interesting results for the first example we passed in an all lowercase Wednesday and then asked the enum class to try parsing it well because Wednesday is all lowercase it turns out that the default behavior for trip parse is to expect proper casing and that means that it did not parse properly which we can see by this false right here but what is interesting is that the default value of the enum is Monday there's no other placeholder like null or none for this enum so the result is that it's going to get set to something in that enum and that's an important thing to keep in mind when you're using tripar is that you really do want to look at the return State because if it was false and then you went
ahead and used that output you would be saying that your Wednesday all lowercase is okay to be parsed to Monday and that's totally not accurate so please ensure that you're looking at the return value of that method because that's going to tell you whether or not you can actually consume this result variable the next two flavors that we looked at involves specifying whether or not we should ignore the casing so for the first one we said let's go ahead and ignore the case and then we passed in an all lowercase Tuesday and that parsing does succeed because we see a true here and as we can see on the left part we do have a proper Tuesday coming back as that enum value now similar but also conversely we did say that ignore case for the last one would be false and then we passed
in an uppercase F on Friday and that's going to give us this expected casing for the enum value so that does par successfully as we might expect so we did not have to ignore the case for that one because the input was in the proper format and that's going to wrap up our super quick look at how we can go from strings to enum types in C it's important to keep in mind that we cannot just do a cast from a string to the enum type so that doesn't work even though it does work for integer variations but so far in this series we've only been looking at really basic enum types what else can we do with enums and furthermore are we using enums properly what are the situations where we should not be using enums so stay tuned for the next video where
we'll jump into something called flags for enums and you can go ahead and watch that right here thanks and we'll see you next time St
Frequently Asked Questions
Why can't I cast a string directly to an enum type in C#?
In C#, you can't cast a string directly to an enum type because the language does not support that operation. While enums can represent both string and integer values, casting works for integers but not for strings. Instead, you need to use methods like TryParse to convert a string to an enum value.
What is the difference between TryParse and Parse methods for enums?
The main difference between TryParse and Parse methods is how they handle failures. TryParse returns a boolean indicating success or failure without throwing an exception, while Parse will throw an exception if the conversion fails. This makes TryParse more convenient for scenarios where you want to avoid exceptions.
How do I ensure that my string parsing is case insensitive when converting to an enum?
To ensure case insensitivity when parsing a string to an enum, you can use the overload of the TryParse method that allows you to specify whether to ignore case. By setting this parameter to true, the method will successfully parse strings regardless of their casing.
These FAQs were generated by AI from the video transcript.