Improving readability of the code with enumerable and yield

You have probably written code like this (I certainly did). The use case is not important (it searches for a text describing an enum value). It tries to search for a value in various locations and until a non-null value is found:

string FindDisplayString(object value, string name)
{
  string displayString = null;
  if (resourceManager != null)
  {
    displayString = resourceManager.GetString($"{type.Name}.{name}");
    if (displayString != null)
    {
      return displayString;
    }

    displayString = resourceManager.GetString($"{type.Name}.{value.ToString()}");
    if (displayString != null)
    {
      return displayString;
    }
  }

  displayString = value.GetDescriptionAttribute(null);
  if (displayString != null)
  {
     return displayString;
  }

  return name ?? value.ToString();
}

Then I realized I can do better by using IEnumerable<string> and yield return:

IEnumerable<string> FindDisplayString(object value, string name)
{
    if (resourceManager != null)
    {
        yield return resourceManager.GetString($"{type.Name}.{name}");
        yield return resourceManager.GetString($"{type.Name}.{value.ToString()}");
    }

    yield return value.GetDescriptionAttribute(null);
    yield return name;
    yield return value.ToString();

    yield break;
}

This time the search is “suspended” on every yield line and won’t continue until next value is required. I then can decide whether to continue of stop:

var result = FindDisplayString(i, Enum.GetName(type, i)).FirstOrDefault(s => s != null);

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Blue Captcha Image
Refresh

*