title: Understanding lazy loading optimization in C#
body: <p>After reading a bit of how yield, foreach, linq deferred execution and iterators work in C#. I decided to give it a try optimizing an attribute based validation mechanic inside a small project. The result:</p>
  
  <pre><code>private IEnumerable&lt;string&gt; GetPropertyErrors(PropertyInfo property)
  {
      // where Entity is the current object instance
      string propertyValue = property.GetValue(Entity)?.ToString();
  
      foreach (var attribute in property.GetCustomAttributes().OfType&lt;ValidationAttribute&gt;())
      {
          if (!attribute.IsValid(propertyValue))
          {
              yield return $"Error: {property.Name} {attribute.ErrorMessage}";
          }
      }
  }
  
  // inside another method
  foreach(string error in GetPropertyErrors(property))
  {
      // Some display/insert log operation
  }
  </code></pre>
  
  <p>I find this slow but that also could be due to reflection or a large amount of properties to process.</p>
  
  <p>So my question is... <strong>Is this optimal or a good use of the lazy loading mechanic?</strong> or I'm missing something and just wasting tons of resources.</p>
  
  <p>NOTE: The code intention itself is not important, my concern is the use of lazy loading in it.</p>