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?
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.