Lazy initialization

Lazy class in .NET 4.0 is a superb implementation for performance enhancement. But one thing that bothers me about it, is the setter property missing for the Lazy objects. You can not set object values once they loaded lazily. And of course, this is due to some strong reasons behind it regarding to the threads. Anyway, I cam up with a custom designed Lazy class through which we can get and set values easily.

public sealed class Lazy<T>
{
private readonly object padlock = new object();
private readonly Func<T> createValue;
private bool isValueCreated;
private T objValue;

public T Value
{
get
{
if (!isValueCreated)
{
lock (padlock)
{
if (!isValueCreated)
{
objValue = createValue();
isValueCreated = true;
}
}
}
else if (!Config.IsCacheOn)
{
lock (padlock)
{
if (!Config.IsCacheOn)
{
objValue = createValue();
isValueCreated = true;
}
}
}
}
set
{
lock (padlock)
{
objValue = value;
isValueCreated = true;
}
}
}

public bool IsValueCreated
{
get
{
lock (padlock)
{
return isValueCreated;
}
}
}

public Lazy(Func<T> createValue)
{
if (createValue == null) throw new ArgumentNullException(“createValue”);

this.createValue = createValue;
}

public override string ToString()
{
return Value.ToString();
}
}

Its declaration:

public class City
{
int id;
LString name;
Lazy<Country> country;

public int ID
{
get { return id; }
set { id = value; }
}

public LString Name
{
get { return name; }
set { name = value; }
}

public Lazy<Country> Country
{
get { return country; }
set { country = value; }
}
}

And, finally its usage:

City item = new City();
item.ID = 1;
int countryID = dr.GetInt32(1);
item.Country = new Common.Lazy<Country>(() =>
{
return GetCountry(countryID);
});

Advertisements

About Saad Khan

Saad is an ASP.NET developer with 4 years of experience, and has also made a number of contributions to the Sitefinity marketplace and community. He loves to explore new code, and create innovative tools and procedures while exploring new approaches in his work with Sitefinity and MVC. As an experienced .NET developer, he frequents both Telerik and Microsoft technologies. In his spare time, Saad is an avid gamer and movie fanatic, and also experiments with new and interesting tools on the Microsoft platform.​​

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: