title: Does the order you declare your class variables affect how memory will be allocated?
body: <p>I came across the following, an excerpt from the book</p>
  
  <blockquote>
    <p>C# 6.0 in a Nutshell by Joseph Albahari and Ben Albahari (O’Reilly).</p>
    
    <p>Copyright 2016 Joseph Albahari and Ben Albahari, 978-1-491-92706-9.</p>
  </blockquote>
  
  <p><a href="https://i.stack.imgur.com/CJ7kQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CJ7kQ.jpg" alt="enter image description here"></a></p>
  
  <p>I do not see it mentioned there, but would it not follow, then, as a rule of thumb - that <strong>you should always declare the variables in your type in descending order of size</strong>, in order <strong>to avoid the memory waste</strong> being pointed out ?</p>
  
  <p>I mean, if I got it right, we should all be normally taking that into consideration when designing our types.</p>
  
  <hr>
  
  <p>Update: </p>
  
  <p>I came up with the snippet below to prove whether the above is right or wrong. I was expecting S2's size to be different, however (to support what the book says).</p>
  
  <pre><code>public struct S1
  {
      public byte b;
      public long l;
  }
  
  public struct S2
  {
      public long l;
      public byte b;
  }
  
  [StructLayout(LayoutKind.Explicit, Size = 9)]
  public struct S3
  {
      [FieldOffset(0)]
      public byte b;
  
      [FieldOffset(1)]
      public long l;
  }
  
  S1 s1 = new S1();
  S2 s2 = new S2();
  S3 s3 = new S3();
  
  Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(s1)); //prints 16
  Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(s2)); //prints 16
  Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(s3)); //prints 9
  </code></pre>