Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

Using Lazy<T> and abstract wrapper class to lazy-load complex system parameters

.NET Framework 4.0 introduced new class called Lazy<T> and I wrote blog post about it: .Net Framework 4.0: Using System.Lazy<T>. One thing is annoying for me – we have to keep lazy loaded value and its value loader as separate things. In this posting I will introduce you my Lazy<T> wrapper for complex to get system parameters that uses template method to keep lazy value loader in parameter class.

 

NB! This blog is moved to gunnarpeipman.com

Click here to go to article

Comments

AndyT said:

I'd prefer this:

public class LazyParameter<T> {

   private readonly Lazy<T> _lazyParam;

   public LazyParameter( Func<T> load ) {

       _lazyParam = new Lazy<T>( load );

   }

   public T Value {

       get { return _lazyParam.Value; }

   }

}

Which is a bit cleaner to use:

var temp = new LazyParameter<int>( () => 1 + 30 ).Value;

var page = new LazyParameter<string>(

   () => HttpContext.Current.Request.QueryString["page"]

).Value;

# November 11, 2011 10:16 AM

DigiMortal said:

Thanks for feedback, AndyT! Your solution is fine when there is not much code in method that retrieves actual value. But in the case of complex logic that needs more code my solution works better because you have separate class with its own methods.

# November 11, 2011 11:12 AM

Markus said:

But Isent the point of lazy loading data the data is ökades when/if the gode hits the parameter?

This code loars the data in the constructor?

How skuld this be used in a buissnes class?

# November 11, 2011 5:32 PM

Markus said:

Ökades would be loaded in english :)

# November 11, 2011 5:33 PM

DigiMortal said:

This code doesn't load data in constructor. Lazy<T> accepts Func as constructor argument but it doesn't run this Func immediately.

When Value is asked then Lazy<T> checks of data is already loaded and if it isn't then it runs this Func to get data.

# November 12, 2011 8:27 AM