[Source: http://geekswithblogs.net/EltonStoneman]
If you make heavy use of lazy-loaded properties, the repetitive if-backing-field-null-then-instantiate code can be centralized in an extension method on the object class:
/// <summary>
/// Extension methods for <see cref=”Object”/>
/// </summary>
public static class ObjectExtensions
{
/// <summary>
/// Lazy-loads a property
/// </summary>
/// <typeparam name=”T”>Type of property</typeparam>
/// <param name=”obj”>Extended object</param>
/// <param name=”field”>Property backing field</param>
/// <param name=”load”>Property loading function</param>
/// <returns>Lazy-loaded property</returns>
public static T LazyLoad<T>(this object obj, ref T field, Func<T> load)
{
if (field == null || field.Equals(default(T)))
{
field = load();
}
return field;
}
}
Classes then define lazy-loaded properties using the extension method, specifying the backing field and the method used to populate it:
protected List<MediaItem> AllItems
{
get
{
return this.LazyLoad<List<MediaItem>>(ref this._allItems,
() => new List<MediaItem>());
}
}
– rather than:
protected List<MediaItem> AllItems
{
get
{
if (this._allItems == null)
{
this._allItems = new List<MediaItem>();
}
return this._allItems;
}
}
Only a tiny enhancement, but it isolates some general code and reduces the chances of causing an infinite loop by typing the property name rather than the field name.