Lazy properties initialization with null coalescing operator
suggest changeprivate 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 ) );
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents