Friday, January 27, 2012

Comparing IPAddress-es

Recently I was struggling with a LINQ expression, where I had a comparison of two ip addresses. Like used to - the comparison was done by the == operator, which was the cause of the headache.
NEVER USE == WITH IPAddress.
Seems IPAddress have no its own overrie for ==, and because it's a reference type that operator is just comparing two addresses(whether those point to the same location in memory or not). And I was getting false for equal ip address comparison.
You can just try to do the following:

bool areEqual = IPAddress.Parse("150.148.1.54") == IPAddress.Parse("150.148.1.54");
// the areEqual now is false

So the proper way to compare them is to use the Equals method, which IPAddress type has an override for:

bool areEqual = IPAddress.Parse("150.148.1.54").Equals(IPAddress.Parse("150.148.1.54"));
// and now the areEqual will be true


Good luck with your coding.

No comments: