Skip to content

Instantly share code, notes, and snippets.

@developerdizzle
Last active May 1, 2018 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save developerdizzle/a5d08a2539cc77450df7 to your computer and use it in GitHub Desktop.
Save developerdizzle/a5d08a2539cc77450df7 to your computer and use it in GitHub Desktop.
Lazy-loading initialization examples
/* Lazy Initialization example 1 */
private decimal? _calculatedNumber;
public decimal CalculatedNumber
{
get
{
if (!_calculatedNumber.HasValue) {
_calculatedNumber = this.CalculateNumber();
}
return _calculatedNumber.Value;
}
}
/* Lazy Initialization example 2 - slimmed down */
private decimal? _calculatedNumber;
public decimal CalculatedNumber
{
get
{
return (_calculatedNumber = _calculatedNumber.HasValue ? _calculatedNumber.Value : this.CalculateNumber());
}
}
/* Lazy Initialization example 3 - database call */
private User _currentUser;
private int _currentUserId;
public User CurrentUser
{
get
{
if (_currentUser == null) {
_currentUser = db.Users.SingleOrDefault(u => u.UserId == _currentUserId);
}
return _currentUser;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment