Programming Newbie Programming Newbie - 1 year ago 85
C# Question

Validate null property before returing

I would like to validate a null property and would like to return an empty string if it is NULL. For that I have created a class like below:

public class TestValue
{
public string CcAlias
{
get
{
return string.IsNullOrEmpty(CcAlias) ? string.Empty : CcAlias;
}
set
{
CcAlias = CcAlias ?? string.Empty;
}
}
}


And tested my class with below code:

private void TestMethod()
{
var testValue = new TestValue();
testValue.CcAlias = null;

MessageBox.Show(testValue.CcAlias);
//I thought an empty string will be shown in the message box.
}


Unfortunately error is coming which is stated below:

System.StackOverflowException was unhandled
HResult=-2147023895
Message=Exception of type 'System.StackOverflowException' was thrown.
InnerException:

Answer Source

Your setter and getter are calling themselves recursively:

set
{
    CcAlias = CcAlias ?? string.Empty;
}

This calls the CcAlias getter which in turn calls itself again (by testing string.IsNullOrEmpty(CcAlias)) and again and again, leading to a StackOverflowException.

You need to declare a backing field and set this in your setter:

public class TestValue
{
    private string __ccAlias = string.Empty; // backing field

   public string CcAlias
   {
        get
        {
            // return value of backing field
            return string.IsNullOrEmpty(_ccAlias) ? string.Empty : _ccAlias;
        }
        set
        {
            // set backing field to value or string.Empty if value is null
            _ccAlias = value ?? string.Empty;
        }
    }
}

So you store your string in a backing field _ccAlias and your getter returns the value of this field.
Your setter now sets this field. The argument for the setter is passed in the keyword value.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download