title: Size of generic structure
body: <p>I need to find out a size of a generic structure (I can not do it like sizeof(T) or using Marshal.SizeOf(...) 0> gives me an error)</p>
  
  <p>So I wrote:</p>
  
  <pre><code>public static class HelperMethods
  {
      static HelperMethods()
      {
          SizeOfType = createSizeOfFunc();
      }
  
      public static int SizeOf&lt;T&gt;()
      {
          return SizeOfType(typeof(T));
      }
  
      public static readonly Func&lt;Type, int&gt; SizeOfType = null;
  
      private static Func&lt;Type, int&gt; createSizeOfFunc()
      {
          var dm = new DynamicMethod("SizeOfType", typeof(int), new Type[] { typeof(Type) });
  
          ILGenerator il = dm.GetILGenerator();
          il.Emit(OpCodes.Ldarg_0);
          il.Emit(OpCodes.Sizeof); //needs to be il.Emit(OpCodes.Sizeof, typeof(something))
          il.Emit(OpCodes.Ret);
  
          var func = (Func&lt;Type, int&gt;)dm.CreateDelegate(typeof(Func&lt;Type, int&gt;));
          return func;
      }
  }
  </code></pre>
  
  <p>A diffuclty is that il.Emit(OpCodes.Sizeof) needs an argument which I can not pass it during the method (SizeOfType) creation. <strong>How can I pass a parameter which is on stack to il.Emit(OpCodes.Sizeof) using IL ?</strong> (or a different solution but I want to cache a function (delegate) not a result what is proposed in the 2nd answer)</p>