Replies: 1 comment 2 replies
-
See Octokit for a real world example of a custom StringEnum type in https://github.com/octokit/octokit.net/blob/50265be680a77ef0871b999d5984fd51e14f0798/docs/working-with-enums.md It uses implicit conversions from strings to The benefit of this approach however is that you can access the unmapped string value. Currently that is impossible in GW2SDK. Example: a new item rarity public enum Rarity
{
Junk,
Basic,
Fine,
Masterwork,
Rare,
Exotic,
Ascended,
Legendary
// Missing Epic
} Usage with StringEnum might look like this: StringEnum<Rarity> rarity = "Epic";
Console.WriteLine( rarity.Value ); // Throws
Console.WriteLine( (Rarity)rarity ); // Throws
Console.WriteLine( rarity.StringValue ); // Epic If throwing is undesired, it might still be a good idea to use a HashCode StringEnum<Rarity> rarity = "Epic";
Console.WriteLine( rarity.Value ); // 126655543
Console.WriteLine( (Rarity)rarity ); // 126655543
Console.WriteLine( rarity.StringValue ); // Epic |
Beta Was this translation helpful? Give feedback.
-
For background: dotnet/csharplang#2849
Consider using "strongly typed strings" instead of int enums.
The current implementation tries to parse strings as enums, or falls back to casting its hashcode to the type of the enum.
A custom algorithm is used to ensure that a string always results in the same hashcode.
From a consumer perspective, it's not great that you can receive enum values without a name.
As a programmer you want to do this:
Instead you're forced to deal with the numeric value until the missing enum member is added.
If nothing else, this looks a bit stupid. There isn't an easy way to obtain the numeric value or its meaning.
Why is Epic equal to 126655543?
It's just the algorithm, bro
On the other hand, the current solution should integrate nicely with existing tools. For example Entity Framework Core knows how to persist enums, even with undefined values.
Strongly typed strings do not enjoy the same level of code reuse. EF Core would try to map the class to a table instead of a column. You would have to set up a Value Conversion for each enum class.
I'm inclined to keep using my hashcode approach but leaving the door open in case something changes or someone comes forward with new insights.
Beta Was this translation helpful? Give feedback.
All reactions