62

How can I write a shorthand of the following scenario?

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

    return _rows;
}
15
  • 14
    Your code is fine as-is. It can be shortened, but at the cost of readability. It's not worth it to save 3 lines in my opinion.
    – Phil K
    Commented Jul 8, 2016 at 13:31
  • 29
    I'm not crazy about this pattern. You have a getter that produces a state change Commented Jul 8, 2016 at 13:54
  • 13
    @BradThomas It's not so bad in some patterns. The example in the question looks a bit like lazy evaluation: the get doesn't change the external state of the object. As long as _rows is not accessed from somewhere else, that is... Commented Jul 8, 2016 at 13:58
  • 10
    @KABoissonneault And as long as this object is never read by multiple threads simultaneously Commented Jul 8, 2016 at 18:38
  • 7
    @Tavian. The problems are more insidious than that. Its generally good for the consumer of a getter to be able to assume that the object is in the same state before and after the property is read. Otherwise surprising side effects can occur, violating the Principle of Least Astonishment. Commented Jul 8, 2016 at 19:04

11 Answers 11

81

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.

14
  • 20
    return _rows ?? (_rows = new List<Row>());
    – eocron
    Commented Jul 8, 2016 at 12:40
  • 12
    @hvd the documentation provided for ?? is more than clear. I can't see any need to rephrase the clear docs in my own words.
    – Zein Makki
    Commented Jul 9, 2016 at 17:37
  • 19
    @hvd The OP wanted a shorthand, this is exactly what this answer provides.
    – Zein Makki
    Commented Jul 9, 2016 at 17:52
  • 5
    @hvd so you don't like ?? ? This is not the place to debate on whether this feature is useful or not in terms of readability.
    – Zein Makki
    Commented Jul 9, 2016 at 17:56
  • 6
    Well, I think in this case it's still quite readable and if you know the ?? operator it shouldn't be a problem to understand it.
    – Stefan
    Commented Jul 9, 2016 at 18:40
41

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.

2
  • 1
    Though instantiating a list is so cheap that this is silly. Commented Jul 10, 2016 at 15:03
  • 3
    I went with what the OP used in his question. I assumed this is just an example and the actual object is more heavy. Commented Jul 10, 2016 at 15:07
20

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>();
2
  • 5
    The C#6 solution is the way to go. Commented Jul 8, 2016 at 23:35
  • For the C# 6, I prefer to generally put new in constructors for easier debugging.
    – Phil1970
    Commented Jul 12, 2016 at 1:47
18

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.

3
  • 3
    In the case of an empty list like here, there's not much difference. However, that's not always true in general. What if the initialization of the object takes longer, and you (as the author of the library) are not sure if it's ever requested by the calling program. Then this method will introduce too much overhead and lazy loading is the way to go.
    – Mr Lister
    Commented Jul 10, 2016 at 11:55
  • Simpler is better. Users never have to test for null, and you don't have to document it. At least for List (I agree with Lister), and for the first version unless you know otherwise, it's likely premature optimization (or something an automated can do for you). Don't spend time thinking about it. Commented Jul 10, 2016 at 14:46
  • @MrLister If lazy loading is required because of some performance overhead, then this question chose poorly to replace it with an empty list initialization; a more appropriate choice would be something like MyExpensiveToInitializeClass. This answer applies to the question as written, and assumes that there are no reasons for doing this beyond what is written. If there are, that would be a different question.
    – jpmc26
    Commented Jul 11, 2016 at 0:02
12
List<Row> _rows;
public List<Row> Rows => _rows ?? (_rows = new List<Row>());
10

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

5

Like this for example:

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

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.

1
return _rows ?? (_rows = new List<Row>());
2
  • 3
    or shorter: return _rows == null? new List<Row> : _rows
    – nosbor
    Commented Jul 8, 2016 at 12:39
  • 3
    @nosbor both of these continue to return a new instance of a list as they leave _rows unassigned, which is different behavior than the OP is asking for.
    – Andy
    Commented Jul 8, 2016 at 23:26
0

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

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

        return _rows;
    }
5
  • 2
    better not, really
    – edc65
    Commented Jul 8, 2016 at 14:38
  • 3
    I'm not sure why this is getting downvoted. Sure, it doesn't actually do anything apart from shortening the source code, but still. Removing curly braces from one-statement if statements is considered a good thing by many.
    – Mr Lister
    Commented Jul 10, 2016 at 12:00
  • @MrLister It's not really any better. It's the same code.
    – PC Luddite
    Commented Jul 10, 2016 at 18:52
  • @PCLuddite It certainly is shorter, is it not? :) Commented Jul 11, 2016 at 12:46
  • 2
    This is the best answer Commented Jul 12, 2016 at 19:32
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.