{"id":3563,"date":"2012-03-20T10:38:10","date_gmt":"2012-03-20T08:38:10","guid":{"rendered":"https:\/\/ingmarverheij.com\/?p=3563"},"modified":"2012-03-20T10:38:10","modified_gmt":"2012-03-20T08:38:10","slug":"using-objects-as-key-in-hashtable","status":"publish","type":"post","link":"https:\/\/ingmarverheij.com\/en\/using-objects-as-key-in-hashtable\/","title":{"rendered":"Using objects as key in HashTable"},"content":{"rendered":"\n<p><a href=\"https:\/\/en.wikipedia.org\/wiki\/Hash_table\" target=\"_blank\"><img loading=\"lazy\" decoding=\"async\" style=\"background-image: none; border-right-width: 0px; margin: 0px 0px 0px 5px; padding-left: 0px; padding-right: 0px; display: inline; float: right; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px\" title=\"\" border=\"0\" alt=\"\" align=\"right\" src=\"https:\/\/ingmarverheij.com\/wp-content\/uploads\/2012\/03\/380px-Hash_table_5_0_1_1_1_1_0_SP_svg.png\" width=\"117\" height=\"92\" \/><\/a>A <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/aahzb21x.aspx\" target=\"_blank\">HashTable<\/a> can be used to store a collection of key\/value pairs. The key object is used to uniquely identify the key\/value pair which makes is easy to store data like a database.<\/p>\n<p>The type of the key <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/system.object.aspx\" target=\"_blank\">object<\/a> which is <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/system.collections.hashtable.add.aspx\" target=\"_blank\">added<\/a> to the HashTable is variable. It can be an <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/system.int32.aspx\" target=\"_blank\">integer<\/a>, a <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/system.string.aspx\" target=\"_blank\">string<\/a>, a <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/system.guid.aspx\" target=\"_blank\">GUID<\/a> etc. Because of the nature of a <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/system.guid.aspx\" target=\"_blank\">GUID<\/a> (a globally unique identifier) it is an ideal candidate for a key object.<\/p>\n<p>If you want to use a combination of two (or more) <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/system.guid.aspx\" target=\"_blank\">GUIDS<\/a> as a key object you can create a class object, but there is a caveat.<\/p>\n<p><!--more--><\/p>\n<h4>Example #1 \u2013 How you shouldn\u2019t use it<\/h4>\n<p>Let\u2019s take create two GUID objects, called <font face=\"Courier New\">objKey1<\/font> and <font face=\"Courier New\">objKey2<\/font>, and fill them with a GUID.<\/p>\n<pre lang=\"vb.net\">Dim objKey1 As Guid = New Guid(&quot;423baa7b-4f46-4b42-b3e8-498e11099544&quot;)\nDim objKey2 As Guid = New Guid(&quot;f0bcf839-4349-4ff2-8695-6a91df86cabb&quot;)<\/pre>\n<p>Now where going to create a hashtable called <font face=\"Courier New\">objHashTable<\/font> where the key\/value pairs are stored.<\/p>\n<pre lang=\"vb.net\">Dim objHashTable As New Hashtable()<\/pre>\n<p>Because we want to store two GUID\u2019s as a key object where going to create a simple class called ValueKey.<\/p>\n<pre lang=\"vb.net\">Private Class ValueKey\n   Public Key1 As Guid\n   Public Key2 As Guid\n   Public Sub New(Key1ID As Guid, Key2ID As Guid)\n       Key1 = Key1ID\n       Key2 = Key2ID\n   End Sub\nEnd Class<\/pre>\n<p>Now let\u2019s add a key\/value pair to the hashable<\/p>\n<pre lang=\"vb.net\">objHashTable.Add(objKey, Date.Now)<\/pre>\n<p>The hashtable <font face=\"Courier New\">objHashTable<\/font> now contains <strong>one<\/strong> key\/value pair. We can check if the key object we\u2019ve just added is in the hashtable:<\/p>\n<pre lang=\"vb.net\">Debug.Print(&quot;Key found #1 : &quot; &amp; objHashTable.ContainsKey(objKey))<\/pre>\n<p><font face=\"Courier New\">Key found #1 : True<\/font><\/p>\n<p>Okay, as expected. Now let\u2019s create a new object key with exact the same content (<font face=\"Courier New\">objKey1<\/font> and <font face=\"Courier New\">objKey2<\/font>) <\/p>\n<pre lang=\"vb.net\">objKey = New ValueKey(objKey1, objKey2)<\/pre>\n<p>Since the content of the key is exactly the same (objKey1 and objKey2 isn\u2019t changed) you expect the key to be present in the hashtable:<\/p>\n<pre lang=\"vb.net\">Debug.Print(&quot;Key found #2 : &quot; &amp; objHashTable.ContainsKey(objKey))<\/pre>\n<p><font face=\"Courier New\">Key found #1 : False<\/font><\/p>\n<p>That was NOT the expected result. Although the content of the key object is equal, the hashtable can\u2019t find the key object. <\/p>\n<h4>&#160;<\/h4>\n<h4>Example #2 \u2013 How you should use it<\/h4>\n<p>The problem in example 1 is caused by the uniqueness of the <font face=\"Courier New\">KeyValue<\/font> class. If you compare the two objects with <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/bsc2ak47.aspx\" target=\"_blank\">Object.Equals<\/a> method you\u2019ll notice they are not equal. If the objects are not equal, the key value in the hashtable will never match. <\/p>\n<p>The solution lies in the KeyValue class, it needs an override for the <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/bsc2ak47.aspx\" target=\"_blank\">Equals<\/a> (and <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/system.object.gethashcode.aspx\" target=\"_blank\">GetHashCode<\/a>) method.<\/p>\n<p>So let\u2019s use the same code as in example 1 but add an override for the <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/bsc2ak47.aspx\" target=\"_blank\">Equals<\/a> and <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/system.object.gethashcode.aspx\" target=\"_blank\">GetHashCode<\/a> in the <font face=\"Courier New\">KeyValue<\/font> class.<\/p>\n<pre lang=\"vb.net\">Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load\n    Dim objKey1 As Guid = New Guid(&quot;423baa7b-4f46-4b42-b3e8-498e11099544&quot;)\n    Dim objKey2 As Guid = New Guid(&quot;f0bcf839-4349-4ff2-8695-6a91df86cabb&quot;)\n    Dim objHashTable As New Hashtable()\n    Dim objKey As New ValueKey(objKey1, objKey2)\n    objHashTable.Add(objKey, Date.Now)\n    Debug.Print(&quot;Key found #1 : &quot; &amp; objHashTable.ContainsKey(objKey))\n\n    objKey = New ValueKey(objKey1, objKey2)\n    Debug.Print(&quot;Key found #2 : &quot; &amp; objHashTable.ContainsKey(objKey))\n    End\nEnd Sub\n\nPrivate Class ValueKey\n    Public Key1 As Guid\n    Public Key2 As Guid\n    Public Sub New(Key1ID As Guid, Key2ID As Guid)\n        Key1 = Key1ID\n        Key2 = Key2ID\n    End Sub\n    Public Overrides Function Equals(ByVal obj As Object) As Boolean\n       If obj Is Nothing OrElse Not [GetType]().Equals(obj.GetType()) Then Return False\n       Return (Key1.Equals(obj.Key1)) And (Key2.Equals(obj.Key2))\n    End Function\n    Public Overrides Function GetHashCode() As Integer\n       Return (BitConverter.ToInt32(Key1.ToByteArray, 0) \/ 2) + (BitConverter.ToInt32(Key2.ToByteArray, 0) \/ 2)\n    End Function\nEnd Class<\/pre>\n<p><font face=\"Courier New\">Key found #1 : True<\/font><\/p>\n<p><font face=\"Courier New\">Key found #2 : True<\/font><\/p>\n","protected":false},"excerpt":{"rendered":"<p>A HashTable can be used to store a collection of key\/value pairs. The key object is used to uniquely identify the key\/value pair which makes is easy to store data like a database. The type of the key object which is added to the HashTable is variable. It can be an integer, a string, a [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"site-container-style":"default","site-container-layout":"default","site-sidebar-layout":"default","disable-article-header":"default","disable-site-header":"default","disable-site-footer":"default","disable-content-area-spacing":"default","footnotes":""},"categories":[312],"tags":[439,437,438],"class_list":["post-3563","post","type-post","status-publish","format-standard","hentry","category-vb-net-scripting","tag-equals","tag-hashtable","tag-object"],"_links":{"self":[{"href":"https:\/\/ingmarverheij.com\/en\/wp-json\/wp\/v2\/posts\/3563","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ingmarverheij.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ingmarverheij.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ingmarverheij.com\/en\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/ingmarverheij.com\/en\/wp-json\/wp\/v2\/comments?post=3563"}],"version-history":[{"count":1,"href":"https:\/\/ingmarverheij.com\/en\/wp-json\/wp\/v2\/posts\/3563\/revisions"}],"predecessor-version":[{"id":3564,"href":"https:\/\/ingmarverheij.com\/en\/wp-json\/wp\/v2\/posts\/3563\/revisions\/3564"}],"wp:attachment":[{"href":"https:\/\/ingmarverheij.com\/en\/wp-json\/wp\/v2\/media?parent=3563"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ingmarverheij.com\/en\/wp-json\/wp\/v2\/categories?post=3563"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ingmarverheij.com\/en\/wp-json\/wp\/v2\/tags?post=3563"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}