I just found out about yield return, it seems very nice to me. I use it in a method like this:
public IEnumerable<ValidationResult> Validate(ValidationContext vc)
{
if (Name == "Arbitary")
yield return new ValidationResult("Bad Name.", new[] { "Name" });
else if (Email == "BadEmail")
yield return new ValidationResult("Bad Email.", new [] {"Email" });
}
However, I need to modify this method to return some ValidationResults from the child method. Without use, the yieldcode would look like this:
public override IEnumerable<ValidationResult> Validate(ValidationContext vc)
{
List<ValidationResult> retVal = new List<ValidationResult>();
Validator.TryValidateObject(this, vc, retVal, true);
if (Name == "Arbitary")
retVal.Add(new ValidationResult("Bad Name.", new[] { "Name" }));
else if (Email == "BadEmail")
retVal.Add(new ValidationResult("Bad Email.", new[] { "Email" }));
return retVal;
}
Is it possible to rewrite this with yield?
source
share