xx77aBs
xx77aBs

Reputation: 4768

Is this good way of using .NET's System.Lazy

    private Lazy<Image> _headshot = new Lazy<Image>(LoadHeadshotFromHDD);

    public Image Headshot
    {
        get
        {
            return _headshot.Value;
        }
        set
        {
            _headshot = new Lazy<Image>(() => value);
        }
    }

Let's say I have a Person class and Headshot property is in that class. Headshot is loaded from HDD so I want it to be lazy, but I also want to implement setter for that property. Will there be a problem with the way that I've implemented this? I'm just not sure that I'm using it correctly.

Upvotes: 1

Views: 204

Answers (2)

khellang
khellang

Reputation: 18102

There's really no point in using lazy loading if you already have the object in memory (in the setter case), but it's perfectly fine to do it this way. One thing I can think of, is if you'd check the _headshot.IsValueCreated, it'll return false, even though you already have the object in memory. Another alternative would be

private Image _headshot;

public Image Headshot
{
    get { return _headshot ?? (_headshot = LoadHeadshotFromHDD()); }
    set { _headshot = value; }
}

This will lazy load the headshot when the property is accessed, just like when using Lazy<T>, but it'll set the value directly, so you can check _headshot != null instead of _headshot.IsValueCreated. You should check out Jon Skeet's Singleton Pattern post.

Upvotes: 4

Wiktor Zychla
Wiktor Zychla

Reputation: 48230

Looks ok, however, if you'd take the initialization to the constructor, you could have less code.

public class Foo
{
    public Foo()
    {
        this.Headshot = new Lazy<Image>( () => LoadHeadshotFromHDD );
    }

    public Lazy<Image> Headshot { get; set; }
}

Upvotes: 0

Related Questions