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.

  1. public Person FindPerson(Criteria c)  
  2. {  
  3.     Lazy<Person> person = new Lazy<Person>();  
  4.     // Code to actually find a person ...  
  5.     // ... and populate person.Value  
  6.     return person.IsValueCreated ? person.Value : null;  
  7. }  
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.
  1. foreach (Font font in GetFixedFonts())  
  2. {  
  3.     // But GetFixedFonts returned null.  
  4. }  
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.
  1. public FontFamily[] GetFixedFonts()  
  2. {  
  3.     Lazy<List<FontFamily>> fonts = new Lazy<List<FontFamily>>();  
  4.   
  5.     foreach (FontFamily ff in System.Drawing.FontFamily.Families)  
  6.         if (IsFixedFontFamily(ff))  
  7.             fonts.Value.Add(ff);  
  8.   
  9.     return fonts.Value.ToArray();  
  10. }  

1 comment(s) :

Thank you for sharring

1:09 AM  

Newer Post Older Post Home

Blogger Syntax Highliter