Method having yield return is not throwing exception

前端 未结 1 1333
暖寄归人
暖寄归人 2021-01-18 13:08

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?

相关标签:
1条回答
  • 2021-01-18 13:36

    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.

    0 讨论(0)
提交回复
热议问题