Check null or empty string

14,134

Solution 1

just use value in your setter to handle the correct behavior

set
{
    if (string.IsNullOrEmpty(value))
        this.reason = "reason not explicited";
    else 
        this.reason = value;
}

Solution 2

Because you are checking the property instead of the value.
Your current code sets the value of the property only if it's null or empty.
It should be

    set
    {
        if (string.IsNullOrEmpty(value))
            this.reason = "reason not explicited";
        else this.reason = value;
    }

Or even better:

    set
    {
        this.reason = (string.IsNullOrEmpty(value)) ? "reason not explicited": value;
    }

Solution 3

You have to check value, not this.Reason:

public string Reason
    {
        get
        {
            return this.reason;
        }
        set
        {
            this.reason = string.IsNullOrEmpty(value)
              ? "reason not explicited"
              : value; 
        }
    }

Solution 4

The problem is in this line of code

if (string.IsNullOrEmpty(this.Reason))

When you are trying to get the value of this property, calls it's getter, which returns value of reason field. And this field is not filled with correct value at the moment you are trying to get value of it.

So you should modify your code to check if null or empty string of concrete input value:

if (string.IsNullOrEmpty(value))
Share:
14,134
louisdeck
Author by

louisdeck

Updated on June 13, 2022

Comments

  • louisdeck
    louisdeck almost 2 years

    I would like to display 'reason not explicited' if the user doesn't fill this field or the user input if he fills it. With this code, I don't understand why but even if I fill the field, it is going to display 'reason not explicited'.

        private string reason;
        public string Reason
        {
            get
            {
                return this.reason;
            }
            set
            {
                if (string.IsNullOrEmpty(this.Reason))
                    this.reason = "reason not explicited";
                else this.reason = value;
            }
        }
    
        [Pure]
        public static bool IsNullOrEmpty(String value) {
            return (value == null || value.Length == 0);
        }
    
    • Dmitry Bychenko
      Dmitry Bychenko about 7 years
      if (string.IsNullOrEmpty(value)) this.reason = "reason not explicited" ...;
    • Igor
      Igor about 7 years
      Use some basic client side validation instead to display the appropriate validation message. You can also use property attributes if you are using mvc validation. Do not hard code this into your model logic.
  • Myrtle
    Myrtle about 7 years
    Getter should not change values.
  • M. Adeel Khalid
    M. Adeel Khalid about 7 years
    Wrong solution.
  • ATC
    ATC about 7 years
    I wouldn't recommend it. Getter should return actual value.