ipnetwork
ipnetwork copied to clipboard
Equality behaviour
I'm encountering some unexpected behaviour with these two IPv6 addresses:
- 2a01:430:277::/64
- 2a01:430:277::10
- When using
Equals()
andCompare()
these two IP addresses are classed as equal. (The code is not checking the_ipAddress
property.)
https://github.com/lduchosal/ipnetwork/blob/f41f06c8881d60ab7232dce66d1af1830bb9d22b/src/System.Net.IPNetwork/IPNetwork.cs#L1941-L1951
- When adding them to a HashSet, they both are added. However if they were equal as the previous equality check shows, then there should only be one. (The code is checking the
_ipAddress
property.)
https://github.com/lduchosal/ipnetwork/blob/f41f06c8881d60ab7232dce66d1af1830bb9d22b/src/System.Net.IPNetwork/IPNetwork.cs#L1531-L1533
- If
_ipAddress
is important enough to be used as part ofGetHashCode()
then should it be exposed as a property? Currently when comparing the available properties they appear to be equal (example displaying the contents of the HashSet via PowerShell):
Network : 2a01:430:277::
AddressFamily : InterNetworkV6
Netmask : ffff:ffff:ffff:ffff::
Broadcast :
FirstUsable : 2a01:430:277::
LastUsable : 2a01:430:277:0:ffff:ffff:ffff:ffff
Usable : 18446744073709551616
Total : 18446744073709551616
Cidr : 64
Network : 2a01:430:277::
AddressFamily : InterNetworkV6
Netmask : ffff:ffff:ffff:ffff::
Broadcast :
FirstUsable : 2a01:430:277::
LastUsable : 2a01:430:277:0:ffff:ffff:ffff:ffff
Usable : 18446744073709551616
Total : 18446744073709551616
Cidr : 64
Happy to help with a PR to fix this but would appreciate a second pair of eyes on what the correct fixes are here.
I'm fairly sure the fix should be to remove using _ipAddress
as part of generating the hash code. I've performed manual tests and run all unit tests which pass successfully.
Just reading in https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-define-value-equality-for-a-type that Microsoft's recommendation is "Override Object.GetHashCode so that two objects that have value equality produce the same hash code."
I realise that may break some applications so would probably need a major semver release.
Hello,
Thanks for pointing this out. Looks like a bug and your proposal seems good. Can you check branch : fix/gethashcode ?
I will merge this in a few. Best regards
@lduchosal Have reviewed and checked against my test case, and PR looks good. Thank you!