10

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:

VS Code type hinting suggesting 3 possible values.

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.

1
  • 1
    Whether or not this is literally an enumerated type is irrelevant. You have an enumeration of strings as a de facto enum, so it still applies. Commented Jun 29, 2018 at 15:57

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

9 Comments

While I generally agree with this answer, it doesn't really address this particular point without more research on the asker's part: My value is still technically a string as well, which is what I need to use with the JSON API requests and responses. Unless you were FGITW'ing and were going to add that in an edit...
@mattferderer you should still use enums, just use JSON.net for serialization / parsing and provide this property attribute to your enum values.
JSON.NET can take care of serializing and deserializing the enum with StringEnumConverter.
Then you should go with @afrazier 's suggestion. Use enum converter for JSON serialization.
If you weren't using JSON and serialization, why would you still care about its string value? Refactor the rest of your code to expect an enum, it's better practice in C#.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.