C#.NET objects and memory model — estimate the size of an instance (ignoring object header).
namespace CuriousTabConsoleApplication
{
class Baseclass
{
private int i;
protected int j;
public int k;
}
class Derived : Baseclass
{
private int x;
protected int y;
public int z;
}
class MyProgram
{
static void Main(string[] args)
{
Derived d = new Derived();
}
}
}
What is the size contribution of the fields in one Derived object if each int is 4 bytes (ignore header/alignment)?
-
A24 bytes
-
B12 bytes
-
C20 bytes
-
D10 bytes
-
E16 bytes
Answer
Correct Answer: 24 bytes
Explanation
Introduction / Context:The question focuses on field layout through inheritance and simple size estimation for primitive fields in C#. It intentionally asks for the size contributed by the fields (not the true runtime size including headers/padding).
Given Data / Assumptions:
- All six fields across base and derived are
int. - Each
intoccupies 4 bytes. - We ignore CLR object header, method table pointer, and padding/alignment for this estimate, as directed by the question.
Concept / Approach:A derived object contains the instance fields of its base classes plus its own fields. Access modifiers (private/protected/public) do not change whether the storage exists; they only change visibility.
Step-by-Step Solution:
Baseclass fields:i, j, k → 3 * 4 = 12 bytes.Derived fields: x, y, z → 3 * 4 = 12 bytes.Total field bytes in a Derived object: 12 + 12 = 24 bytes.Verification / Alternative check:Reflect over the type and count instance fields; you will find six int fields. Tools like ILDASM or reflection confirm field presence irrespective of access level.
Why Other Options Are Wrong:12 or 16 bytes ignore some fields; 20 bytes is a miscount; 10 bytes is not a multiple of 4 and physically impossible for six ints.
Common Pitfalls:Confusing accessibility with allocation, and forgetting base-class fields are part of the derived instance layout.
Final Answer:24 bytes