Is there a shorthand way to return values that might be null?

How can I write a shorthand of the following scenario?

get
{
    if (_rows == null)
    {
        _rows = new List<Row>();
    }

    return _rows;
}

Solution 1:

Using null-coalescing operator ( ?? ):

get 
{ 
     _rows = _rows ?? new List<Row>(); 
     return _rows; 
}

OR (less readable):

get { return _rows ?? (_rows = new List<Row>()); }

The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.

Solution 2:

This is the lazy initialization pattern so the straightforward way would be to use the Lazy<T> class.

class Foo
{
    Lazy<List<Row>> _rows;

    public Foo()
    {
        _rows = new Lazy(() => new List<Row>());
    }

    public List<Row> Rows
    {
        get { return _rows.Value; }
    }
}

This has the additional advantage that it doesn't "pollute" the getter with initialization logic.

Solution 3:

I suggest ternary operator

get {
  return _rows == null ? _rows = new List<Row>() : _rows;
}

Or since empty List<Row> doesn't bring much overhead why not get rid of explicit _row field and implement just read-only property (C# 6.0 syntax):

public IList<Row> Rows {get;} = new List<Row>();

Solution 4:

Here's a better idea: Prevent _rows from ever being null.

Make your constructor initialize the variable:

public MyClass()
{
    this._rows = new List<Row>();
}

and then your property is just

get
{
    return this._rows;
}

Make sure that if you need to "clear" the variable, you always call its Clear method or assign a new empty list instead of assigning null. Maybe encode that operation in a method if you really need to make it clear and consistent throughout the class.

This is much more logical. If your variable should never be null, it should never be null. It also neatly avoids both the conditional and the issue of having a getter modify state.