title: Using BinaryWriter in a generic class
body: <pre><code>[Serializable]
  public class Vector3D&lt;T&gt; {
      public T x;
      public T y;
      public T z;
  }
  </code></pre>
  
  <p>I have this simple Vector class that's used to store coordinates in various numerical types.</p>
  
  <p>I need to read this from a file and then later store it.</p>
  
  <p>It usually looks something like this:</p>
  
  <pre><code>someCoord = new Vector3D&lt;int&gt; {
                  x = reader.ReadInt32(),
                  y = reader.ReadInt32(),
                  z = reader.ReadInt32()
              };
  writer.Write(someCoord.x);
  writer.Write(someCoord.y);
  writer.Write(someCoord.z);
  </code></pre>
  
  <p>I would love to turn those lines into something like this:</p>
  
  <pre><code>someCoord = new Vector3D&lt;int&gt;(reader);
  someCoord.Write(writer);
  </code></pre>
  
  <p>I would have Read and Write methods ready in the Vector3D class. While writing isn't a problem since I can do something like:</p>
  
  <pre><code>writer.Write((T)x)
  </code></pre>
  
  <p>Trying to read in the same fashion becomes a problem since I have to call methods with distinct names, depending on the type I want to read.</p>
  
  <p>All that being said, is there some clever way of still achieving this?
  I was thinking about using delegates, but I can't figure out the syntax.</p>
  
  <p>I'd have a dictionary where I'd keep Type-Function(delegate) pairs so that when I want to read something, I call something like:</p>
  
  <pre><code>T value = reader.dictionary[T]();
  </code></pre>
  
  <p>where reader is an instance of BinaryReader. If T is int, dictionary[T] would be replaced with readInt32, if T was float, dictionary[T] would be replaced with readSingle, etc.</p>
  
  <p>Any idea how to achieve this?</p>