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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…