Showing posts with label custom iterators. Show all posts
Showing posts with label custom iterators. Show all posts

Sunday, July 27, 2008

More fun with 'yield return'

I'm a big fan of custom iterators that were introduced with C# 2.0. I keep on finding new uses for them. Today I was thinking about rendering contact addresses in Suteki Shop. I have a contact that looks like this:

sutekishopContact

Only Firstname, Lastname, Address1 and CountryId are required fields, all the others are optional. Previously I was rendering a contact like this:

sutekishopContactOldRender

If say, Address1, Address2 and Town were missing the contact renders with gaps in it. Also it's a bore writing out each line like that. With 'yield return' I was able to add a custom iterator 'GetAddressLines' to my contact class so that I can simply render out the lines that are available:

sutekishopContactRender

Here's the code:

public IEnumerable<string> GetAddressLines()
{
 yield return Fullname;
 yield return Address1;

 if (!string.IsNullOrEmpty(Address2))
 {
     yield return Address2;
 }

 if (!string.IsNullOrEmpty(Address3))
 {
     yield return Address3;
 }

 if (!string.IsNullOrEmpty(Town))
 {
     yield return Town;
 }

 if (!string.IsNullOrEmpty(County))
 {
     yield return County;
 }

 if (!string.IsNullOrEmpty(Postcode))
 {
     yield return Postcode;
 }

 yield return Country.Name;
}