My class has complicated property:
private Image m_LogoImage=null;
public Image LogoImage
{
get
{
if (m_LogoImage == null && File.Exists(Data.LogoFileUrl))
{
DrawingImage image = DrawingImage.FromFile(Data.LogoFileUrl);
m_LogoImage = Image.GetInstance(image, new Color(1, 1, 1));
}
return m_LogoImage;
}
}
LogoImage.get is very slow and resource consuming action to the first time the client calls it, the property calculate the image and stored the result in private variable m_LogoImage.
This looks to me very basic. .NET support automatic properties (public string P {get;set;}). Does it support automatic storing of complicated properties?
There’re a number of state based concerns, so there’s no language level mechanics for lazy load.
You can however use the
Lazy<T>class to accomplish this functionality.You can also use the null coalescing operator (
??) to do lazy load for nullable types.