Comparing two Uri’s

This one bit me today a bit unexpectedly.


I was comparing two Uri’s and was getting unexpected matches between two Uri’s that where quite clearly not the same. Turns out the when comparing Uri’s the Fragment, or anchor or part after the #, is not part of the comparison.

So the following unit test passes even though I would have expected it to fail!


public void TestTwoEqualUrisWithDifferentAnchorShouldNotBeEqual()


    var baseUri = new Uri("");

    var uri1 = new Uri(baseUri, "#anchor1");

    var uri2 = new Uri(baseUri, "#anchor2");


    Assert.AreEqual(uri1, uri2);

    Assert.AreNotEqual(uri1.ToString(), uri2.ToString());



Note that when comparing uri1 and uri2 they are equal even though they use two different anchor tags. Comparing the ToString() results does show the difference though. Wasted another bit of time on this piece of trivia [:(]




Leave a Reply

Your email address will not be published. Required fields are marked *