JsonConverter doesn't support string Value type
- Dominant language
- C#
- Stars
- 2.4k
- Forks
- 184
- PR merge metrics
- No merged PRs in 30d
Description
I have a usecase where we need to deal with string values as the backing value for an enumeration. As an example, imagine a Customer Type stored in the database as a string code:
- Preferred = "pref"
- Elite = "el"
- Regular = "reg"
SmartEnum can handle that if you define your type as `SmartEnum`. However the associated SmartEnum.JsonNet package doesn't allow this because it constraints the `TValue` to be a `struct`, which `string` is not.
## Example:
```cs
public class CustomerTypeCode: SmartEnum
{
public static readonly CustomerTypeCode Regular = new CustomerTypeCode(nameof(Regular), "reg");
public static readonly CustomerTypeCode Preferred = new CustomerTypeCode(nameof(Preferred), "pref");
public static readonly CustomerTypeCode Elite = new CustomerTypeCode(nameof(Elite), "el");
public DecisionResponseCode(string name, string value) : base(name, value) { }
}
public class Customer
{
// ERROR: The type 'string' must be non-nullable value type in order to use it as parameter 'TValue' ...
[JsonConverter(typeof(SmartEnumValueConverter))]
public CustomerTypeCode Code { get; set; }
}
```
I get a compiler error when trying to use either `SmartEnumValueConverter` or `SmartEnumNameConverter` because the generic type constraints of `TValue` include `struct`, whereas `TValue` in SmartEnum doesn't have this constraint.
```cs
public abstract class SmartEnum
: IEquatable>,
IComparable>
where TEnum : SmartEnum
where TValue : IEquatable, IComparable
```
```cs
public class SmartEnumValueConverter
: JsonConverter
where TEnum : SmartEnum
where TValue : struct, IEquatable, IComparable
```
Is there any reason to not use `string` as your backing value, that this type constraint is in place? Or can the restriction be removed in a future update? For now I can write my own type converter, but I figured I'd submit this as a bug (in case it is one).
Thanks!
Contributor guide
Research direction
Start with SmartEnumValueConverter and SmartEnumNameConverter from the SmartEnum.JsonNet package, then compare their TValue constraints with SmartEnum. The issue is done when the CustomerTypeCode example can use string as its backing value and the relevant converter supports it without the current struct constraint.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100