In .NET 4 the following snippet with a cached property can also be written using the System.Lazy<T>
class. I measured the performance of both approaches and it's pretty much the same. Is there any real benefit or magic for why I should use one over the other?
Cached Property
public static class Brushes
{
private static LinearGradientBrush _myBrush;
public static LinearGradientBrush MyBrush
{
get
{
if (_myBrush == null)
{
var linearGradientBrush = new LinearGradientBrush { ...};
linearGradientBrush.GradientStops.Add( ... );
linearGradientBrush.GradientStops.Add( ... );
_myBrush = linearGradientBrush;
}
return _myBrush;
}
}
}
Lazy<T>
public static class Brushes
{
private static readonly Lazy<LinearGradientBrush> _myBrush =
new Lazy<LinearGradientBrush>(() =>
{
var linearGradientBrush = new LinearGradientBrush { ...};
linearGradientBrush.GradientStops.Add( ... );
linearGradientBrush.GradientStops.Add( ... );
return linearGradientBrush;
}
);
public static LinearGradientBrush MyBrush
{
get { return _myBrush.Value; }
}
}
Lazy<T>
you're beingLazy
to write your own implementation. (In a good way, of course.) – ChokecherryProperty<T>
class for backing fields that supports this and more common backing field behavior. – Logography