Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a single element from an iterator block - Iterator cannot contain return statement

Let's say I have the following method. In some came

    public IEnumerable<ValidationResult> Validate(UserLoginCommand command)
    {
        User user = userRepository.Get(u => u.Email == command.UserEmail);
        if(user != null)
        {
            if(!user.Activated)
            {
                return new IEnumerable<ValidationResult>() {new ValidationResult("NotActived", Resources.UserNotActivated)};
            }

            if(user.IsPasswordIncorrent)
            {

                yield return new ValidationResult("IncorrectPassword", Resources.IncorrentPassword);

            }

        }
    }

The actual situation is actually a bit more complex but I've left a lot out for illustration purposes.

The point is in some cases, I want to iterator to continue collecting multiple errors...but in other cases there is a fatal error and I only want to return a single error but it will not let me:

Iterator cannot contain return statement 

What should I do?

like image 447
parliament Avatar asked Dec 19 '12 21:12

parliament


People also ask

Does yield break return null?

1. "yield break" breaks the Coroutine (it's similar as "return"). "yield return null" means that Unity will wait the next frame to finish the current scope. "yield return new" is similar to "yield return null" but this is used to call another coroutine.

What is iterator in C#?

An iterator is a method in C# which is used in an array or in collections like the list, etc. to retrieve elements one by one. Or in other words, we can say that an iterator is used to perform an iteration over the collections.

What is yield break?

You can think of yield break as a return statement which does not return a value. For example, if you define a function as an iterator, the body of the function may look like this: for (int i = 0; i < 5; i++) { yield return i; } Console.


1 Answers

If you just want to return a collection of size one, you can do this:

if(!user.Activated)
{
  yield return new ValidationResult("NotActived", Resources.UserNotActivated);
  yield break;
}
like image 79
Paul Phillips Avatar answered Sep 28 '22 17:09

Paul Phillips