I’m working in C# with some JSON & an API. I'm wondering how to handle something like this.
One of the JSON values is a string that can be one of the following values: “Last_Day”, “Last_Week”, “Last_Month”.
In TypeScript I can do this:
type DateSince = "Last_Day" | "Last_Week" | "Last_Month"
Then I get type hinting like this:
If the value is anything but those 3 strings, I get the red squiggle line error. My value is still technically a string as well, which is what I need to use with the JSON API requests and responses.
I have yet to find a great way to do this in C#. Is it even possible to do this in C# with relative ease?
My ideal solution lets me assign a custom type to a variable instead of using a string. This way I don't have to remember the possible string values.
In C# you can use Enums.
public enum DateSince
{
Last_Day ,
Last_Week,
Last_Month
}
Usage:
var datesince = DateSince.Last_Day;
Read more about C# Enums
As suggested by @PatrickRoberts & @afrazier, the best way is using enums and the Json.NET StringEnumConverter.
[JsonConverter(typeof(StringEnumConverter))]
public enum DateSince
{
[EnumMember(Value = "LAST_DAY")]
LastDay,
[EnumMember(Value = "LAST_WEEK")]
LastWeek,
[EnumMember(Value = "LAST_MONTH")]
LastMonth,
}
Customizing Enumeration Member Values
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With