I have a Blazor component for creating graphs with ChartJs. Based on the models, C# creates a Json for the Chart configuration. I use the System.Text.Json to convert the class to a Json. Some configurations have defined values that I can use: for example, the PointStyle accepts only few values such as circle and cross.
For this reason, I want to have the constraint to select only the accepted values for this configuration. Then, in my project I created a class PointStyle to have a sort of enum with string.
public class PointStyle
{
private PointStyle(string value) { Value = value; }
public string Value { get; private set; }
public static PointStyle Circle { get { return new PointStyle("circle"); } }
public static PointStyle Cross { get { return new PointStyle("cross"); } }
}
To obtain the correct Json configuration, in the main model I created 2 properties: PointStyle and PointStyleString.
[JsonIgnore]
public PointStyle? PointStyle {
get => _pointStyle;
set
{
_pointStyle = value;
PointStyleString = _pointStyle.Value;
}
}
private PointStyle? _pointStyle;
[JsonPropertyName("pointStyle")]
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string? PointStyleString { get; set; }
PointStyle accepts only the values in the defined list but this is ignored from the Json converter. For example, I can configure this like
PointStyle = PointStyle.Cross
Then, the public variable PointStyleString contains the string I have to serialize in the Json and this is updated when the PointStyle sets a new value.
Now, I have to read the property Value from the class PointStyle that contains the string I have to pass to the configuration. For this reason, I have a private variable _pointStyle that saves the value for PointStyle; so, when a new value is set, I also set the PointStyleString.
Everything I described above is working but it seems to me quite complicated for just setting a value. Do you think I can simplify this code?