title: Serializing a dictionary in C#
body: <p>I have a class named serializableVector2:</p>
  
  <pre><code>[Serializable]
  class serializableVector2
  {
      public float x, y;
      public serializableVector2(int x, int y)
      {
          this.x = x;
          this.y = y;
      }
  }
  </code></pre>
  
  <p>and I have a struct named savedMapTile:</p>
  
  <pre><code>[Serializable]
  struct savedMapTile
  {
      public oreInstance ore;
      public int backgroundTileId;
      public int playerId;
      public tree tree;
  }
  </code></pre>
  
  <p>and I have a dictionary using these two classes:</p>
  
  <pre><code>[SerializeField]
  Dictionary&lt;serializableVector2, savedMapTile&gt; savedTiles;
  </code></pre>
  
  <p>I am trying to load this dictionary modify it, and then save it again all using serialization.</p>
  
  <p>I am deserializing the dictionary like so:</p>
  
  <pre><code>FileStream f = File.Open(saveFileName, FileMode.Open);
  BinaryFormatter b = new BinaryFormatter();
  savedTiles = (Dictionary&lt;serializableVector2, savedMapTile&gt;)b.Deserialize(f);
  f.Close();
  </code></pre>
  
  <p>and I am serializing it like so:</p>
  
  <pre><code>FileStream f = File.Open(saveFileName, FileMode.Create);
  BinaryFormatter b = new BinaryFormatter();
  b.Serialize(f, savedTiles);
  f.Close();
  </code></pre>
  
  <p>However, when I try to access an element in the dictionary that I know should exist I get the following error: </p>
  
  <blockquote>
    <p>System.Collections.Generic.KeyNotFoundException: The given key was not
    present in the dictionary.</p>
  </blockquote>
  
  <p>I get this error from running this code:</p>
  
  <pre><code>id = (savedTiles[new serializableVector2(-19,13)].backgroundTileId);
  </code></pre>
  
  <p>What I find really strange is that I am able to print out the entirety of the dictionaries keys and its values as well. This is where I am getting the values -19 and 13 for the Vector2. I print the keys and values like so:</p>
  
  <pre><code>for (int i = 0; i &lt; 100; i++ )
  {
      UnityEngine.Debug.Log(vv[i].x +" "+vv[i].y);
      UnityEngine.Debug.Log(x[i].backgroundTileId);
  }
  </code></pre>
  
  <p>At this point I'm really stumped, I have no clue what is going on. I can see the file being saved in windows explorer, I can access keys and values in the dictionary, but I cant seem to use it properly. It is also important to note that when I use the .Contains() method on the dictionary in a similar way to how I am trying to access a value, it always returns false.</p>
  
  <p>This is for a Unity 5 project, using C# in visual studio running on windows 8.1. </p>