C#.NET — How many bytes does the following struct instance occupy? (Assume a 32-bit process / 4-byte object references.) class Trial { int i; Decimal d; } struct Sample { private int x; // 4 bytes private Single y; // 4 bytes private Trial z; // reference (pointer) → 4 bytes on 32-bit } Sample samp = new Sample();

Difficulty: Medium

Correct Answer: 12 bytes

Explanation:


Introduction / Context:
Struct size depends on the sizes of its fields and alignment rules. Reference-type fields inside a struct store only a reference (pointer), not the referenced object's inline data.



Given Data / Assumptions:

  • We assume a 32-bit CLR process (common for textbook questions), so references are 4 bytes.
  • Fields: int (4), Single/float (4), reference to Trial (4).
  • No explicit packing attributes; default alignment applies.


Concept / Approach:
Total size is the sum of field sizes plus any padding required to satisfy alignment. Here, the natural layout 4 + 4 + 4 = 12 requires no additional padding for 32-bit alignment, so the struct occupies 12 bytes.



Step-by-Step Solution:

Compute sizes: int = 4.Single (float) = 4.Reference to Trial = 4 (pointer size on 32-bit).Sum = 4 + 4 + 4 = 12 bytes.


Verification / Alternative check:
Use System.Runtime.InteropServices.Marshal.SizeOf(typeof(Sample)) in a 32-bit process to confirm 12. In a 64-bit process, the size would be 16 (pointer = 8), which is why the assumption matters.



Why Other Options Are Wrong:

  • 8 bytes: Too small; ignores one or more fields.
  • 16/20/24 bytes: Do not match the 32-bit pointer assumption and alignment here.


Common Pitfalls:
Counting the in-memory size of the referenced object Trial inside the struct; only the reference is stored in the struct.



Final Answer:
12 bytes

More Questions from Structures

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion