Category Archives: Uncategorized

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);