Sometimes you want a function to return an object or null if no object is found. Lazy evaluation makes it easy to automate this behaviour.

public Person FindPerson(Criteria c)
{
    Lazy<Person> person = new Lazy<Person>();
    // Code to actually find a person ...
    // ... and populate person.Value
    return person.IsValueCreated ? person.Value : null;
}
This is fairly ellegant. If no person is found lazy evaluation assures that the object is never created and related resources are not spent. Be careful though! Here's a common pest.
foreach (Font font in GetFixedFonts())
{
    // But GetFixedFonts returned null.
}
The fictional GetFixedFonts() function called in code bellow returns Font[] collection. You assume it will always return a non- null value. But then on a bad day it doesn't and your code breaks with an exception.

You can assure that function always returns an array /even if empty/ by using lazy evaluation too. Here is an example of that.
public FontFamily[] GetFixedFonts()
{
    Lazy<List<FontFamily>> fonts = new Lazy<List<FontFamily>>();

    foreach (FontFamily ff in System.Drawing.FontFamily.Families)
        if (IsFixedFontFamily(ff))
            fonts.Value.Add(ff);

    return fonts.Value.ToArray();
}

1 comment(s) :

Thank you for sharring

1:09 AM  

Newer Post Older Post Home

Blogger Syntax Highliter