123
123

Reputation: 41

memory allocation of base variabels when derived object is created in c#?

where are member variables of base class stored when an object of derived class is created in c# ?

 using System;
 class A
 {
   public int i;
 }
 class B:A
 {
   public int j;
   static public void Main()
   {
       B b = new B();
   }
 }

Here when b object is created where is i variable stored in the heap ?does it store in the instance of the b itself or separately ?

Upvotes: 1

Views: 223

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500785

You're creating a single object (on the heap), with all the fields declared in the type hierarchy. I believe it's implementation-specific what order they're stored in, but it wouldn't surprise me to see all the fields in the base class, followed by the fields declared in the derived class, etc. (That way the offset for the field for any given declared type would always be the same regardless of the execution-time type.)

So the memory layout might look something like:

  • Object header / sync block
  • Method table pointer
  • Field i
  • Field j

But to answer the most direct part of your question: all the values that make up the state of the object are stored together, regardless of which type each field is declared in.

Upvotes: 2

Related Questions