ErrorAgain
ErrorAgain

Reputation: 755

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;
}

Upvotes: 62

Views: 8005

Answers (11)

Abdul Moiz Khan
Abdul Moiz Khan

Reputation: 703

You can do this by any of the following ways:

  • Conditional operator (?:)
  • Null-coalescing operator ( ?? )

With Conditional operator

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

Null-coalescing operator

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

Upvotes: 0

Roman Reiner
Roman Reiner

Reputation: 1109

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.

Upvotes: 41

Zein Makki
Zein Makki

Reputation: 30022

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.

Upvotes: 81

jpmc26
jpmc26

Reputation: 29874

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.

Upvotes: 18

Dmitriy Kovalenko
Dmitriy Kovalenko

Reputation: 3616

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

Upvotes: 1

user743382
user743382

Reputation:

If you want your code to behave like your current code, lazily initialising your backing field when the property is accessed, then yes, you can make it shorter. You can rename your backing field, as answered already use ?? to put everything in a single expression, and when you have that single expression, use C# 6's new property syntax to avoid writing get and return:

List<Row>_;List<Row> Rows=>_??(_=new List<Row>());

Hopefully, well before you get to this point, you will see that you've turned easy-to-understand code that does exactly what you want into a horrible mess that you would never want to maintain.

Just keep your code exactly as it is. You can make it shorter, as shown, but that doesn't make it any better.

If the problem is that it takes more time to write, because you keep typing the same code over and over, many IDEs provide some feature to insert templates, snippets, or whatever term they use for it. This lets you define something along the lines of

{Type} {Field};
public {Type} {Property} {
  get {
    if ({Field} == null) {
      {Field} = new {Type}();
    }
    return {Field};
  }
}

where your editor will then prompt you for the specific {Type}, {Field}, {Property}, without having to type it again each time.

Upvotes: 3

Richard Ev
Richard Ev

Reputation: 54117

As others have said, you can use the null-coalescing operator in this scenario.

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

It's worth noting that this is the kind of change that ReSharper is great at suggesting (they call it a quick-fix).

In your example it will put a small squiggle under the if statement. Hovering over it reveals a suggestion for how the code could be changed/simplified.

Convert to '??' expression

A couple of clicks later, and the change is implemented.

enter image description here

Upvotes: 10

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186698

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

Upvotes: 20

Tyler Nichols
Tyler Nichols

Reputation: 196

If you really wanted to shorten it I would just remove the extra brackets.

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

        return _rows;
    }

Upvotes: 0

Sinatr
Sinatr

Reputation: 21999

List<Row> _rows;
public List<Row> Rows => _rows ?? (_rows = new List<Row>());

Upvotes: 12

eocron
eocron

Reputation: 7536

Like this for example:

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

Upvotes: 5

Related Questions