Enum Capabilities
Hello there!
I was wondering if there is a way to return the string value (either description or name) rather than the enumeration value of an enum.
Take this enum for example:
public enum SourceType
{ SourceLink = 1, Channel = 2, Video = 3 }.
When I return this model:
public class Source
{ string Title; SourceType Type; },
I wonder if the value of the property Type can be string, the name of the enum (SourceLink, Channel or Video) or the description, rather than the integer value (1, 2, 3).
Has anyone done something similar? Is that even possible?
20 Replies
Just call
ToString()
on the enum333fred
REPL Result: Success
Result: List<string>
Compile: 358.326ms | Execution: 78.940ms | React with ❌ to remove this embed.
However, you probably don't want the type of
Source.Type
to be stringThat is when setting the value. I'm wondering if it can be a global config, like in the Startup class of a WebApi. Something automated, without having to use .ToString
You probably just want to call
ToString()
when you displayI return that Source model to front (react app), so I want the Type to be sent as the value of ToString, without having to make it string? Or is this whole part unnecessary?
Ah, you're looking to change how the type serializes?
ChatGPT suggested JsonConverter attribute, but I am not sure about that
yes!
How are you sending it? Json?
Or some other serialization format?
Yeah, it's json
Which json framework? System.Text.Json?
I believe. I do not specify anything, just return the model from the api. I believe it is System.Text
I am not really familiar with the details :/
Trying to learn
333fred
REPL Result: Success
Result: List<string>
Compile: 449.685ms | Execution: 53.823ms | React with ❌ to remove this embed.
Like so
That did not really do the work for me. But I figured out I can use StringEnumConverter (Netwonsoft.Json) and it handles it well.
I can pass either the integer value or the string representation, and it knows how to parse it (on post request), and the response has the respective string representation.
May I ask if that is a good approach?
according to chatGPT, using StringEnumConverter, the cons are:
I'm not sure if that is a huge issue for not so huge application ?
@333fred sorry for the ping, but I would appreciate your opinion!
Hard to say whether your application will be hurt by the perf or not
Then you're using newtonsoft.json, not system.text.json
Yes, now I am. I tried your suggestion, but it doesn't seem to do the work (at least not what I am looking for...)
How may I conclude if it does or not?
$tias
fair
thank you for your help <3