Friday, November 28, 2008

Lazy loading class




///
/// Lazy loading class. When the value is required object will ask for item provider and cache result.
///

/// Item type.
/// Key type.
internal class LazyLoadingBase
{
public delegate TItem GetItemWithNameDelegate(TKey name);

GetItemWithNameDelegate getItemWithName;

TKey key;
TItem item;
bool itemSet;

public LazyLoadingBase(GetItemWithNameDelegate GetItemWithName)
{
itemSet = false;
item = default(TItem);
getItemWithName = GetItemWithName;
}

public object Value
{
get
{
if (!itemSet)
{
item = getItemWithName(key);
itemSet = true;
}
return item;
}

set
{
if (value is TItem)
{
item = (TItem)value;
itemSet = true;
}
else if (value is TKey)
{
key = (TKey)value;
}
else
{
throw new InvalidOperationException();
}
}
}

///
/// Cast operator.
///

public static implicit operator TItem(LazyLoadingBase lazyLoadingBaseObject)
{
return (TItem)lazyLoadingBaseObject.Value;
}
}


No comments: