title: Convert byte array to generic value type?
body: <p>I have a <code>Stream</code> where I'd like to read data from (as value type segments) and move the position according to the size of the given type (declared as generics).</p>
  
  <p>My current approach:</p>
  
  <pre><code>public byte ReadUInt8(Stream stream) {
      return (byte)stream.ReadByte();
  }
  
  public ushort ReadUInt16(Stream stream) {
      return (ushort)((ReadUInt8() &lt;&lt; 8) | ReadUInt8());
  }
  
  ...
  </code></pre>
  
  <p>What I'd like to achieve:</p>
  
  <pre><code>public TValue Read&lt;TValue&gt;(Stream stream)
      where TValue : struct
  {
      var bufferSize    = Marshal.SizeOf(typeof(TValue));
      var buffer        = new byte[bufferSize];
  
      if(stream.Read(buffer, 0, bufferSize) == 0)
          throw new EndOfStreamException();
  
      return (TValue)buffer; // here's where I'm stuck
  
      // EDIT1: A possible way would be
      //        return (TValue)(object)buffer;
      //        but that feels like kicking puppies :/
  }
  </code></pre>
  
  <p>Is this somehow possible? Are there any drawbacks from using <code>Marshal.SizeOf()</code> (performance-wise etc.)?</p>