title: Why sizeof of a struct is unsafe
body: <p>The <a href="http://msdn.microsoft.com/en-us/library/eahchzkf%28v=vs.80%29.aspx">MSDN</a> clearly states</p>
  
  <blockquote>
    <p>For all other types, including structs, the sizeof operator can only
    be used in unsafe code blocks.</p>
  </blockquote>
  
  <p>The <a href="http://www.microsoft.com/en-us/download/confirmation.aspx?id=7029">C# Language Specification</a> is even more precise :</p>
  
  <ol>
  <li>The order in which members are packed into a struct is unspecified.</li>
  <li>For alignment purposes, there may be unnamed padding at the beginning
  of a struct, within a struct, and at the end of the struct.</li>
  <li>The contents of the bits used as padding are indeterminate.</li>
  <li>When applied to an operand that has struct type, the result is the total number of bytes in a variable of that type, including any padding.</li>
  </ol>
  
  <p>However how would the CLR handle the following structures :</p>
  
  <pre><code>[StructLayout(LayoutKind.Explicit, Size = 1, Pack = 1)]
  public struct MyStruct
  {
      [FieldOffset(0)] public byte aByte;
  }
  
  public struct MyEmptyStruct { }
  </code></pre>
  
  <p>In <code>MyStruct</code> we enforce the layout explicitly, the size and how to pack it via the <code>StructLayout</code> attribute. This structure is <em>supposed</em> to have a size of 1 byte in memory.</p>
  
  <p>On the other hand <code>MyEmptyStruct</code> is empty, we can assume that the size in memory will be 0 bytes - even if a such structure is most likely not going to be used it still is an interesting case.</p>
  
  <p>When trying to compute the size of theses structures using <code>sizeof(MyStruct)</code> and <code>sizeof(MyEmptyStruct)</code> the compiler throws the following error :</p>
  
  <blockquote>
    <p>'<em>*</em>' does not have a predefined size, therefore sizeof can only
    be used in an unsafe context</p>
  </blockquote>
  
  <p>I would like to know <strong>why</strong> using <code>sizeof</code> in this context is considered <code>unsafe</code>. The question is not intended to ask for workarounds nor the <em>correct</em> way to compute the size of a struct but rather to focus on the causes.</p>