Home > database >  Graceful way of allowing one of two allowed values in string C#
Graceful way of allowing one of two allowed values in string C#

Time:12-06

I have a request class which has the following property

        /// <summary>
        /// First time discount flag
        /// </summary>
        [JsonProperty("firstTimeDiscountFlag")]
        public string FirstTimeDiscountFlag { get; set; }

I am doing this to check if it is null and has allowed values

 if(string.IsNullOrWhiteSpace(request.FirstTimeDiscountFlag)
   || (request.FirstTimeDiscountFlag.ToUpper() != "Y" && request.FirstTimeDiscountFlag.ToUpper() != "N"))

Is there a better way to handle this?

CodePudding user response:

Here is may be the solution

Create another property in the class

/// <summary>
    /// First time discount flag
    /// </summary>
    [JsonProperty("firstTimeDiscountFlag")]
    public string FirstTimeDiscountFlag { get; set; }

    public bool IsFirstTimeDiscountFlagValid
    {
        get
        {
            if (string.IsNullOrWhiteSpace(FirstTimeDiscountFlag) ||
                (FirstTimeDiscountFlag.ToUpper() != "Y" &&
                 FirstTimeDiscountFlag.ToUpper() != "N")
                 )
            {
                return true;
            }
            return false;
        }
    }

Use like that

  if(request.IsFirstTimeDiscountFlagValid){
      //perform your operation
    }

CodePudding user response:

You could write this as an expression bodied property like this...

public string FirstTimeDiscountFlag { get; set; }
    
public bool IsFirstTimeDiscountFlagValid => 
    string.IsNullOrEmpty(FirstTimeDiscountFlag) || "YN".Contains(FirstTimeDiscountFlag.ToUpper());

But a better approach might be to investigate the Fluent Validation library (https://github.com/FluentValidation/FluentValidation) and write a validator for you model class.

CodePudding user response:

The proper approach is to use a JsonConverter that will serialize a boolean to Y or N and handle the deserialization too:

public class YNBoolConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
    {
        writer.WriteValue(value switch
        {
            true => "Y",
            false => "N",
            _ => string.Empty
        });
    }

    public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
    {
        return reader.Value switch
        {
            true => true,
            "Y" => true,
            "y" => true,

            false => false,
            "N" => false,
            "n" => false,

            _ => existingValue
        };
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(string);
    }
}

You use it via the JsonConverterAttribute:

{
    [JsonConverter(typeof(YNBoolConverter))]
    public bool? BoolValue { get; set; }
}

Working demo available here.

  • Related