Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method having yield return is not throwing exception

Tags:

c#

I have this code in visual studio that when the argument is null will not throw the exception and I cannot figure out why! Is the yield return messing with it somehow?

IEnumerable<string> Method(string s)
{
    if(string == null)
    {
        throw new Exception();
    }

    if(dictionary.TryGetValue(s, out list))
    {
        foreach(string k in list)
        {
            yield return k;
        }
    }
}
like image 816
LrndED Avatar asked Feb 10 '17 01:02

LrndED


1 Answers

You have iterator, which will not be executed until you start enumerating (i.e. consume) it. To get an exception you can call this method in foreach statement, or use some LINQ operator with immediate execution (ToList, ToArray, First etc):

foreach(var s in Method(null))
// or
Method(null).ToList();

Further reading yield (C# Reference)

If you want to validate parameters immediately, then you should split this method into two methods:

public IEnumerable<string> Method(string s)
{
    if(s == null)
       throw new ArgumentNullException(nameof(s));

    return MethodIterator(s);
}

private IEnumerable<string> MethodIterator(string s)
{
    if(dictionary.TryGetValue(s, out list))
    {
        foreach(string k in list)
           yield return k;
    }
}

In this case outer method is simple method and it will be executed immediately (thus we'll get argument check). Another method is still iterator and it will have deferred execution, but it will receive already validated argument.

like image 191
Sergey Berezovskiy Avatar answered Oct 08 '22 23:10

Sergey Berezovskiy