title: C# Marshal byte array to struct
body: <p>I find many answers to my question and they all work. My question is are they all equal in speed and memory. How can I tell what is faster and uses less memory. I don't normally use the Marshal and GCHandle classes. So I am totally green. </p>
  
  <pre><code>public static object RawDeserializer(byte[] rawData, int position, Type anyType)
          {
              int rawsize = Marshal.SizeOf(anyType);
              if (rawsize &gt; rawData.Length)
                  return null;
              IntPtr buffer = Marshal.AllocHGlobal(rawsize);
              Marshal.Copy(rawData, position, buffer, rawsize);
              object retobj = Marshal.PtrToStructure(buffer, anyType);
              Marshal.FreeHGlobal(buffer);
              return retobj;
          }
  
  public static T RawDeserializer&lt;T&gt;(byte[] rawData, int position = 0)
          {
              int rawsize = Marshal.SizeOf(typeof(T));
              if (rawsize &gt; rawData.Length)
              {
                  throw new DataMisalignedException("byte array is not the correct size for the requested type");
              }
              IntPtr buffer = Marshal.AllocHGlobal(rawsize);
              Marshal.Copy(rawData, position, buffer, rawsize);
              T retobj = (T)Marshal.PtrToStructure(buffer, typeof(T));
              Marshal.FreeHGlobal(buffer);
              return retobj;
          }
  
  
  public static T RawDeserializer&lt;T&gt;(byte[] bytes) where T : struct
          {
              T stuff;
              GCHandle handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
              try
              {
                  stuff = Marshal.PtrToStructure&lt;T&gt;(handle.AddrOfPinnedObject());
              }
              finally
              {
                  handle.Free();
              }
              return stuff;
          }
  
  </code></pre>
  
  <p>I am getting the desired results form all 3 implementations.</p>