I was trying to use Enumerable.SequenceEqual(x,y) as I expected it to work based on
Object.Equals(x,y) method, which returns false if x or y is null, and true if both are null (for null cases).
However Enumerable.SequenceEqual(x,y) throws exception if any parameter is a null reference and will not return true if it is given two nulls.
In my code I check for collection equality quite often so I created a method that mimics Object.Equals behaviour for sequences but I just wonder whats the logic behind such default behaviour, and is there maybe an existing method with no exceptions on nulls?
Well, the MSDN documentation explicitly states that it throws an
ArgumentNullExceptionin case any one of the passed in sequences is null. I assume it’s to keep consistency with “standard behaviour” where an object throws aNullReferenceExceptionwhen you try to dereference it. Consider this:This would be ok as
SequenceEqualis an extension method and therefore can handle a null object but it would also be confusing. Every extension method provided by Linq follows this behaviour as far as I know. Also you don’t need to handle special null cases for every extension method (you would need to agree about sensible behaviour and add additional logic and maintain and test it). Saying that it is illegal makes it more robust (against logic bugs) and consistent from a framework perspective. I use Linq a lot and never ran into that problem – I just make sure all my sequences are not null. Reduces code clutter a lot (removes lots of null checks from the code).