System.Collections.Generic.HashSet does not work as advertised

Danny 20 Reputation points
2025-12-17T12:15:18.8933333+00:00

Consider following code which demonstrates the usage of System.Collections.Generic.HashSet:code 1

HashSet does not hash the key's value when doing "contains" lookup. If we change the key's value, it has no bearing on the lookup.

Developer technologies | VB
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 82,146 Reputation points Volunteer Moderator
    2025-12-17T17:06:28.4866667+00:00

    the value stored in the hash set is an object (integer array) reference. Changing an array element does not change the array’s reference. You would need to recreate the array itself to change its value.

    Dim v = key ‘v references key
    key(1) = 6
    if v = key then 
        MessageBox.Show(“still match”)
    end if
    

    Note: if the array was a read only .net structure, then changing an element value would change the value. But I believe this is only available in c#.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.