I've got a C# string extension method that should return an IEnumerable<int> of all the indexes of a substring within a string. It works perfectly for its intended purpose and the expected results are returned (as proven by one of my tests, although not the one below), but another unit test has discovered a problem with it: it can't handle null arguments.

Here's the extension method I'm testing:

public static IEnumerable<int> AllIndexesOf(this string str, string searchText) { if (searchText == null) { throw new ArgumentNullException("searchText"); } for (int index = 0; ; index += searchText.Length) { index = str.IndexOf(searchText, index); if (index == -1) break; yield return index; } }

Here is the test that flagged up the problem:

[TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void Extensions_AllIndexesOf_HandlesNullArguments() { string test = "a.b.c.d.e"; test.AllIndexesOf(null); }

When the test runs against my extension method, it fails, with the standard error message that the method "did not throw an exception".

This is confusing: I have clearly passed null into the function, yet for some reason the comparison null == null is returning false . Therefore, no exception is thrown and the code continues.

I have confirmed this is not a bug with the test: when running the method in my main project with a call to Console.WriteLine in the null-comparison if block, nothing is shown on the console and no exception is caught by any catch block I add. Furthermore, using string.IsNullOrEmpty instead of == null has the same problem.

Why does this supposedly-simple comparison fail?