Elton Stoneman

  Home  |   Contact  |   Syndication    |   Login
  123 Posts | 0 Stories | 3755 Comments | 0 Trackbacks

News

Archives

Post Categories

[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

Feedback

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


Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: