Home > OS >  checking in the model for nulls
checking in the model for nulls

Time:08-03

I like to check the model for nulls before I use the value in the view. Is this the correct way to use the get and set? I am getting an Exception of type 'System.StackOverflowException' was thrown." on the this.MiddleInitial = value;

Model

public string MiddleInitial {
    get {
        if (string.IsNullOrWhiteSpace(MiddleInitial) == true) {
            return MiddleInitial;

        }
        return $ "{MiddleInitial.Trim()}.";

    }
    set {
        this.MiddleInitial = value;
    }
}

Updated Model

public string MiddleInitial {
    get {
        if (string.IsNullOrWhiteSpace(MiddleInitial) == true) {
            return MiddleInitial;

        }
        return $ "{MiddleInitial.Trim()}.";

    }
    set {
        if (string.IsNullOrWhiteSpace(MiddleInitial) == true) {
            return MiddleInitial;

        }
        return $ "{MiddleInitial.Trim()}.";
    }
}

CodePudding user response:

Using an internal private backing field for the property allows you a fine control on what goes into the property and what you return back

// The blank value should be the default for the property
private string _middleInitial = "";

public string MiddleInitial 
{
    get { return _middleInitial; }

    // When someone tries to set a new value for the property
    // check for Invalid values (in this case a null ) and
    // reset the property back to the default 
    // (or even throw an exception if it is the case)
    set 
    { 
        _middleInitial = (value == null ? "" : value.Trim()); 
        // if(value == null)
        //    throw new ArgumentException("Null is not accepted");
        // else 
        //    _middleInitial = value.Trim();
    }
}

CodePudding user response:

Inside your get method's if condition, you should check false, not true. Like below:

get
            {
                //if (string.IsNullOrWhiteSpace(MiddleInitial) == true)
                if (string.IsNullOrWhiteSpace(MiddleInitial) == false)
                {
                    return MiddleInitial;

                }
                return $"{MiddleInitial.Trim()}.";

            }
  • Related