-
-
Save developerdizzle/a5d08a2539cc77450df7 to your computer and use it in GitHub Desktop.
Lazy-loading initialization examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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