Code Trivia #2

What will happen when the following code executes?

enum Status { OK, KO }

static void Main(string[] args)
{
    var results = Parse(null);
}

static IEnumerable<Status> Parse(string[] values)
{
    if (values == null)
        throw new ArgumentNullException("values");

    foreach (var value in values)
    {
        yield return (Status)Enum.Parse(typeof(Status), value);
    }
}

Update:

Yes, the code throwing an ArgumentNullException would be too obvious. The code executes without throwing any exception because since the Parse method has a yield return statement it behaves as an iterator and execution of code in a iterator block only occurs when the enumerator object’s MoveNext method is invoked.

Iterating through the results would execute the code and throw the expected exception. In order to not hide subtle functionality like this the best thing to do would be to implement this method in two parts, one public and the other private.

public static IEnumerable<Status> Parse(string[] values)
{
    if (values == null)
        throw new ArgumentNullException("values");

    return ParseIterator(values);
}

private static IEnumerable ParseIterator(IEnumerable values)
{
    foreach (var value in values)
    {
        yield return (Status)Enum.Parse(typeof(Status), value);
    }
}
Advertisements

8 thoughts on “Code Trivia #2”

  1. I belief an ArgumentNullException would get throwed with the message “values”. But that would be too obvious i guess? 🙂

  2. Yes, I agree with tom. And, sincerely I don’t see another option but VS maybe will. Can i use it? 0:)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s