title: C# - struct serialization
body: <p>I have got a small class that I would like to use for serializing structs. I would like to know two things:</p>
  
  <ul>
  <li><p>Performance issue. Since I am passing <code>Object</code> - it passes just a reference, not a copy of the struct? And since I am returning object of type <code>T</code> it also only passes a reference?</p></li>
  <li><p>Correctness issue. Will this serialization work for all structs? I mean - is there a possibility where those methods will not work?</p>
  
  <pre><code>public static byte[] ToByteArray(Object obj)
  {
      int size = Marshal.SizeOf(obj);
      byte[] arr = new byte[size];
      IntPtr ptr = Marshal.AllocHGlobal(size);
  
      Marshal.StructureToPtr(obj, ptr, true);
      Marshal.Copy(ptr, arr, 0, size);
      Marshal.FreeHGlobal(ptr);
  
      return arr;
  }
  
  public static T ToStructure&lt;T&gt;(byte[] arr) where T : new()
  {
      T str = new T();
  
      int size = Marshal.SizeOf(str);
      IntPtr ptr = Marshal.AllocHGlobal(size);
  
      Marshal.Copy(arr, 0, ptr, size);
      str = (T)Marshal.PtrToStructure(ptr, str.GetType());
      Marshal.FreeHGlobal(ptr);
  
      return str;
  }        
  </code></pre></li>
  </ul>
  
  <p>Thanks, guys!</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I now specify that these are structs. Nothing is being copied now?</p>
  
  <pre><code>    public static byte[] ToByteArray&lt;T&gt;(ref T str) where T : struct
      {
          int size = Marshal.SizeOf(str);
          byte[] arr = new byte[size];
          IntPtr ptr = Marshal.AllocHGlobal(size);
  
          Marshal.StructureToPtr(str, ptr, true);
          Marshal.Copy(ptr, arr, 0, size);
          Marshal.FreeHGlobal(ptr);
  
          return arr;
      }
  
      public static T ToStructure&lt;T&gt;(byte[] arr) where T : struct
      {
          T str = default(T);
  
          int size = Marshal.SizeOf(str);
          IntPtr ptr = Marshal.AllocHGlobal(size);
  
          Marshal.Copy(arr, 0, ptr, size);
          str = (T)Marshal.PtrToStructure(ptr, str.GetType());
          Marshal.FreeHGlobal(ptr);
  
          return str;
      }
  </code></pre>