Konrad Viltersten Konrad Viltersten - 1 month ago 4
C# Question

Preferred way to set default values of nullable properties?

I'm in a dilemma. The (reduced) task is to redesign the following data holder class

class Stuff
{
public String SomeInfo { get; set; }
}


to accommodate the demand that null mustn't be returned. I can think of two ways to achieve that and after deep consideration of 15 minutes, I simply can't decide which one is to be preferred.

Approach by constructor.

class Stuff
{
public String SomeInfo { get; set; }
public Stuff() { SomeInfo = String.Empty; }
}


Approach by property.

class Stuff
{
private String _SomeInfo;
public String SomeInfo
{
get { return _SomeInfo ?? String.Empty; }
set { _SomeInfo = value; }
}
}


Note that the creation of the Stuff instances might be done using the constructor as well as initialization, if that's of any significance. As far as I'm informed, there won't be any other restrictions (but you know how the customers' specifications not always reflect the reality).

Answer

You can only ensure that null is never returned when you use the property:

class Stuff
{
  private String _SomeInfo;
  public String SomeInfo 
  { 
    get { return _SomeInfo ?? String.Empty; }
    set { _SomeInfo = value; }
  }
}

The same approach is used by text-controls(e.g. in ASP.NET) where the Text property never returns null but String.Empty.

For example(ILSpy):

// System.Web.UI.WebControls.TextBox
public virtual string Text
{
    get
    {
        string text = (string)this.ViewState["Text"];
        if (text != null)
        {
            return text;
        }
        return string.Empty;
    }
    set
    {
        this.ViewState["Text"] = value;
    }
}
Comments