SmartEnumValueConverter does not write the value as a number for TValue of type byte or sbyte
- Dominant language
- C#
- Stars
- 2.4k
- Forks
- 184
- PR merge metrics
- No merged PRs in 30d
Description
Take for example the second smart enum from the [Usage](https://github.com/ardalis/SmartEnum?tab=readme-ov-file#usage) section of this project's readme file with the only difference being that the TValue is of type byte:
```
using Ardalis.SmartEnum;
public sealed class TestEnum : SmartEnum
{
public static readonly TestEnum One = new TestEnum("A string!", 1);
public static readonly TestEnum Two = new TestEnum("Another string!", 2);
public static readonly TestEnum Three = new TestEnum("Yet another string!", 3);
private TestEnum(string name, byte value) : base(name, value)
{
}
}
```
Serialization works fine but the problem happens during deserialization because the enum member's value is actually written as a [string](https://github.com/ardalis/SmartEnum/blob/b0d3d9a68164014ece53c56748f296c718a8cb44/src/SmartEnum.SystemTextJson/SmartEnumValueConverter.cs#L60) instead of a number.
Specifically, an exception (InvalidOperationException) is thrown with the message:
`"Cannot get the value of a token type 'String' as a number".`
This is because (as far as I can tell) the converter's [Write()](https://github.com/ardalis/SmartEnum/blob/main/src/SmartEnum.SystemTextJson/SmartEnumValueConverter.cs#L37) method does not handle cases in which TValue is defined as byte or sbyte. Funnily enough, the [ReadValue()](https://github.com/ardalis/SmartEnum/blob/b0d3d9a68164014ece53c56748f296c718a8cb44/src/SmartEnum.SystemTextJson/SmartEnumValueConverter.cs#L79) method actually does just that!
Also, it seems that the decimal type is being handled in Write() but not in ReadValue().
So, a workaround (until this issue is addressed) would be either using any other number type (integer or floating point) or perhaps defining [this](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonnumberhandling?view=net-9.0) JSON serializer setting as "AllowReadingFromString".
Contributor guide
Research direction
Start in src/SmartEnum.SystemTextJson/SmartEnumValueConverter.cs, inspecting Write() and ReadValue() alongside the linked line references. Reproduce the byte or sbyte deserialization failure and check the decimal handling mismatch; done means numeric values round-trip correctly for these types.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Quiet
- Clarity
- Clearly specified
- Newbie friendliness
- 72/100