Lazy properties initialization with null coalescing operator

suggest change
private List<FooBar> _fooBars;

public List<FooBar> FooBars
{
    get { return _fooBars ?? (_fooBars = new List<FooBar>()); }
}

The first time the property .FooBars is accessed the _fooBars variable will evaluate as null, thus falling through to the assignment statement assigns and evaluates to the resulting value.

Thread safety

This is not thread-safe way of implementing lazy properties. For thread-safe laziness, use the Lazy<T> class built into the .NET Framework.

C# 6 Syntactic Sugar using expression bodies

Note that since C# 6, this syntax can be simplified using expression body for the property:

private List<FooBar> _fooBars;

public List<FooBar> FooBars => _fooBars ?? ( _fooBars = new List<FooBar>() );

Subsequent accesses to the property will yield the value stored in the _fooBars variable.

Example in the MVVM pattern

This is often used when implementing commands in the MVVM pattern. Instead of initializing the commands eagerly with the construction of a viewmodel, commands are lazily initialized using this pattern as follows:

private ICommand _actionCommand = null;
public ICommand ActionCommand =>
   _actionCommand ?? ( _actionCommand = new DelegateCommand( DoAction ) );

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Null-Coalescing Operator:
* Lazy properties initialization with null coalescing operator

Table Of Contents
6 Null-Coalescing Operator
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script