Simple Type Safe Coding in Microsoft’s C#

Posted by Peter Kellner on November 02, 2012 · 2 mins read


I often like to show programming tips around simple things.  Over the years, I’ve found that it is easy to get Lazy and do cutting and pasting type coding, however for reliability and maintainability, it’s important to stick to the principle of less is more.

Below is just a simple pattern I often use when doing something that requires processing over a set of images (or anything) multiple times.

foreach (var rec in imageDetails)
    const string imageTypeFull = "ImageTypeFull";
    const string imageTypeThumb = "ImageTypeThumb";
    foreach (var imageType in new List<string> {imageTypeFull, imageTypeThumb})
        var bytes = imageType == imageTypeFull
                        ? db.DetailBytes.Where(a => a.Id == rec.Id).Select(b => b.DataBytes).
                        : db.DetailBytes.Where(a => a.Id == rec.Id).Select(b => b.DataBytes).

Basically, all through the foreach loop, I check for which imageType I am and do the appropriate thing.  Not a big hint, but something that is easy to forget to do.