ipnetwork icon indicating copy to clipboard operation
ipnetwork copied to clipboard

Equality behaviour

Open alexangas opened this issue 2 years ago • 2 comments

I'm encountering some unexpected behaviour with these two IPv6 addresses:

  • 2a01:430:277::/64
  • 2a01:430:277::10
  1. When using Equals() and Compare() 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

  1. 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

  1. If _ipAddress is important enough to be used as part of GetHashCode() 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.

alexangas avatar Jun 07 '22 09:06 alexangas

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.

alexangas avatar Jun 08 '22 13:06 alexangas

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.

alexangas avatar Jul 19 '22 08:07 alexangas

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 avatar Aug 09 '22 09:08 lduchosal

@lduchosal Have reviewed and checked against my test case, and PR looks good. Thank you!

alexangas avatar Aug 09 '22 16:08 alexangas