April 20, 2011
A quite interesting design pattern is lazy loading which defers the initialization of an object until it's accessed for the first time.Lazy loading magic
In the following sample we will expose an object of our class MyClass with lazy loading:private MyClass _myPropertyValue;
public MyClass MyProperty {
get { return _myPropertyValue ?? (_myPropertyValue = GetTheValue(123)); }
}
Explaining the magic
?? in C# is an operator to ensure that a non-null value is passed.
This example:
if(_myPropertyValue != null) {..can easier be expressed as:
return _myPropertyValue;
}
else {
return defaultValue;
}
return _myPropertyValue ?? defaultValue;
What the lazy loading code does is to check if _myPropertyValue is set, if it is the value is returned. If it's not _myPropertyValue is populated with a value by calling the function GetTheValue() and then is the same value returned. The next time the property is accessed _myPropertyValue will have a value and no new function call is needed.
Notice that (_myPropertyValue = GetTheValue(123)) is surrounded with parenthesis, if ommited the code won't work.
This way to handle lazy loading is called lazy initialization.
Comments
comments powered by Disqus