Lets say I have this extention method:
public static bool HasFive<T>(this IEnumerable<T> subjects) { if(subjects == null) throw new ArgumentNullException('subjects'); return subjects.Count() == 5; }
Do you think this null check and exception throwing is really necessary? I mean, when I use the Count method, an ArgumentNullException will be thrown anyways, right?
I can maybe think of one reason why I should, but would just like to hear others view on this. And yes, my reason for asking is partly laziness (want to write as little as possible), but also because I kind of think a bunch of null checking and exception throwing kind of clutters up the methods which often end up being twice as long as they really needed to be. Someone should know better than to send null into a method :p
Anyways, what do you guys think?
Note: Count() is an extension method and will throw an ArgumentNullException, not a NullReferenceException. See Enumerable.Count<TSource> Method (IEnumerable<TSource>). Try it yourself if you don’t believe me =)
Note2: After the answers given here I have been persuaded to start checking more for null values. I am still lazy though, so I have started to use the Enforce class in Lokad Shared Libraries. Can recommend taking a look at it. Instead of my example I can do this instead:
public static bool HasFive<T>(this IEnumerable<T> subjects) { Enforce.Argument(() => subjects); return subjects.Count() == 5; }
Yes, it will throw an
ArgumentNullException. I can think of two reasons for putting the extra checking in:subjects.Count()and forget to put the check in at that point, you could end up with a side effect before the exception is thrown, which isn’t nice.subjects.Count()at the top, and probably with a message with thesourceparameter name. This could be confusing to the caller ofHasFivewho can see asubjectsparameter name.EDIT: Just to save me having to write it yet again elsewhere:
The call to
subjects.Count()will throw anArgumentNullException, not aNullReferenceException.Count()is another extension method here, and assuming the implementation inSystem.Linq.Enumerableis being used, that’s documented (correctly) to throw anArgumentNullException. Try it if you don’t believe me.EDIT: Making this easier…
If you do a lot of checks like this you may want to make it simpler to do so. I like the following extension method:
The example method in the question can then become:
Another alternative would be to write a version which checked the value and returned it like this:
You can then call it fluently:
This is also helpful for copying parameters in constructors etc:
(You might want an overload without the argument name for places where it’s not important.)