Geeks With Blogs

News This is the *old* blog. The new one is at blog.sixeyed.com
Elton Stoneman
This is the *old* blog. The new one is at blog.sixeyed.com

[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.

Posted on Wednesday, September 23, 2009 1:38 PM Code Snippet | Back to top


Comments on this post: Lazy-Loading with Object Extensions

# re: Lazy-Loading with Object Extensions
Requesting Gravatar...
nice tutorial.i really like the way in how u explained ..so grateful to u for give us this information...
Left by Update News on Oct 14, 2011 3:22 PM

Your comment:
 (will show your gravatar)


Copyright © Elton Stoneman | Powered by: GeeksWithBlogs.net