C
C#10mo ago
Pan!cKk

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
333fred
333fred10mo ago
Just call ToString() on the enum
MODiX
MODiX10mo ago
333fred
REPL Result: Success
public enum SourceType
{ SourceLink = 1, Channel = 2, Video = 3 }
Enum.GetValues<SourceType>().Select(e => e.ToString())
public enum SourceType
{ SourceLink = 1, Channel = 2, Video = 3 }
Enum.GetValues<SourceType>().Select(e => e.ToString())
Result: List<string>
[
"SourceLink",
"Channel",
"Video"
]
[
"SourceLink",
"Channel",
"Video"
]
Compile: 358.326ms | Execution: 78.940ms | React with ❌ to remove this embed.
333fred
333fred10mo ago
However, you probably don't want the type of Source.Type to be string
Pan!cKk
Pan!cKkOP10mo ago
That 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
333fred
333fred10mo ago
You probably just want to call ToString() when you display
Pan!cKk
Pan!cKkOP10mo ago
I 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?
333fred
333fred10mo ago
Ah, you're looking to change how the type serializes?
Pan!cKk
Pan!cKkOP10mo ago
ChatGPT suggested JsonConverter attribute, but I am not sure about that yes!
333fred
333fred10mo ago
How are you sending it? Json? Or some other serialization format?
Pan!cKk
Pan!cKkOP10mo ago
Yeah, it's json
333fred
333fred10mo ago
Which json framework? System.Text.Json?
Pan!cKk
Pan!cKkOP10mo ago
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
MODiX
MODiX10mo ago
333fred
REPL Result: Success
using System;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;

[JsonConverter(typeof(JsonStringEnumConverter<SourceType>))]
public enum SourceType
{ SourceLink = 1, Channel = 2, Video = 3 }

Enum.GetValues<SourceType>().Select(e => JsonSerializer.Serialize(e))
using System;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;

[JsonConverter(typeof(JsonStringEnumConverter<SourceType>))]
public enum SourceType
{ SourceLink = 1, Channel = 2, Video = 3 }

Enum.GetValues<SourceType>().Select(e => JsonSerializer.Serialize(e))
Result: List<string>
[
"\"SourceLink\"",
"\"Channel\"",
"\"Video\""
]
[
"\"SourceLink\"",
"\"Channel\"",
"\"Video\""
]
Compile: 449.685ms | Execution: 53.823ms | React with ❌ to remove this embed.
333fred
333fred10mo ago
Like so
Pan!cKk
Pan!cKkOP10mo ago
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?
builder.Services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
options.SerializerSettings.Converters.Add(new StringEnumConverter());
});

public enum SourceType
{
[Description("Source Link")]
[EnumMember(Value = "Source Link")]
SourceLink = 1,
[Description("Channel")]
[EnumMember(Value = "Channel")]
Channel = 2,
[Description("Video")]
[EnumMember(Value = "Video")]
Video = 3
}
builder.Services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
options.SerializerSettings.Converters.Add(new StringEnumConverter());
});

public enum SourceType
{
[Description("Source Link")]
[EnumMember(Value = "Source Link")]
SourceLink = 1,
[Description("Channel")]
[EnumMember(Value = "Channel")]
Channel = 2,
[Description("Video")]
[EnumMember(Value = "Video")]
Video = 3
}
according to chatGPT, using StringEnumConverter, the cons are:
Cons:

Increased Payload Size: String representations generally occupy more space in JSON payloads compared to integer representations, potentially increasing network bandwidth usage and storage requirements.

Performance Overhead: Converting between enum values and strings requires additional processing compared to direct integer serialization/deserialization, which may have a slight impact on performance, especially in high-throughput scenarios.

Parsing Complexity: If using custom string representations, it might introduce parsing complexities, especially when dealing with edge cases or legacy data.

Compatibility with Existing Clients: If the consumers of your JSON data are expecting integer representations of enum values, switching to string representations might require updates on their end.

Loss of Type Safety: Using string representations loses some type safety compared to using integer values, as there's no compile-time check to ensure that the provided string corresponds to a valid enum value.
Cons:

Increased Payload Size: String representations generally occupy more space in JSON payloads compared to integer representations, potentially increasing network bandwidth usage and storage requirements.

Performance Overhead: Converting between enum values and strings requires additional processing compared to direct integer serialization/deserialization, which may have a slight impact on performance, especially in high-throughput scenarios.

Parsing Complexity: If using custom string representations, it might introduce parsing complexities, especially when dealing with edge cases or legacy data.

Compatibility with Existing Clients: If the consumers of your JSON data are expecting integer representations of enum values, switching to string representations might require updates on their end.

Loss of Type Safety: Using string representations loses some type safety compared to using integer values, as there's no compile-time check to ensure that the provided string corresponds to a valid enum value.
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!
333fred
333fred10mo ago
Hard to say whether your application will be hurt by the perf or not Then you're using newtonsoft.json, not system.text.json
Pan!cKk
Pan!cKkOP10mo ago
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?
333fred
333fred10mo ago
$tias
Pan!cKk
Pan!cKkOP10mo ago
fair thank you for your help <3
Want results from more Discord servers?
Add your server