Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
755 views
in Technique[技术] by (71.8m points)

c# - Method having yield return is not throwing exception

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;
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...