Lazy properties initialization with null coalescing C# with Example



Lazy properties initialization with null coalescing C# with Example

operator 
private List _fooBars; 
public List FooBars 
{ 
get { return _fooBars ?? (_fooBars = new List()); } 
} 
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 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 _fooBars; 
public List FooBars => _fooBars ?? ( _fooBars = new List() ); 
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 ) ); 
 

0 Comment's

Comment Form

Submit Comment