Search code examples
c#asp.net-mvcmodel-view-controller

checking in the model for nulls


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()}.";
    }
}

Solution

  • 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();
        }
    }