Check null or empty string
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))
louisdeck
Updated on June 13, 2022Comments
-
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 about 7 years
if (string.IsNullOrEmpty(value)) this.reason = "reason not explicited" ...;
-
Igor about 7 yearsUse 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 about 7 yearsGetter should not change values.
-
M. Adeel Khalid about 7 yearsWrong solution.
-
ATC about 7 yearsI wouldn't recommend it. Getter should return actual value.