Personally, I am a fan of the free syntax interface for IEnumerable / List extension methods in C # as a client. That is, I prefer the syntax as follows:
public void AddTheseGuysToSomeLocal(IEnumerable<int> values) { values.ToList().ForEach(v => _someLocal += v); }
unlike a control structure such as a foreach loop. I find it easier to handle mentally, at a glance. The problem is that my code here will throw null reference exceptions if clients pass me a null argument.
Suppose I donβt want to consider an exclusive null enumeration - I want this to leave some local as-is left - I would add a null protector. But, which is a little syntactically noisy for my taste, and this noise develops in cases when you connect them together in a fluent interface, and intermediate results can also be zero.
So, I created the SafeEnumerableExtensions class, which offers a no-throw guarantee, treating zeros as empty enumerations (lists). Examples of methods include:
//null.ToList() returns empty list public static List<T> SafeToList<T>(this IEnumerable<T> source) { return (source ?? new List<T>()).ToList(); } //x.SafeForEach(y) is a no-op for null x or null y //This is a shortcut that should probably go in a class called SafeListExtensions later public static void SafeForEach<T>(this List<T> source, Action<T> action) { var myAction = action ?? new Action<T>(t => { }); var mySource = source ?? new List<T>(); mySource.ForEach(myAction); } public static void SafeForEach<T>(this IEnumerable<T> source, Action<T> action) { SafeToList(source).SafeForEach(action); }
Now my original method is prettier than if there were a zero defender, but it is also safe, since a zero result in no-op:
public void AddTheseGuysToSomeLocal(IEnumerable<int> values) { values.ForEach(v => _someLocal += v); }
So my question is twofold. (1) I suppose I'm not so original as to be the first to ever think about it - does anyone know if there is an existing library that does this or something like that? And (2) did someone use the specified library or implement a similar scheme and experience unpleasant consequences, otherwise, can anyone foresee unpleasant consequences for doing something like this? Is that even a good idea?
(I found this question when checking for duplicates, but I donβt want to explicitly perform this check on clients - I want the extension class to do this implicitly and not bother clients with this call to additional methods)