8

To be more clear about my question, if you create an array of a particular class: for example,

ExampleClass[] test = new ExampleClass[5]; 

I know the five ExampleClass instances would create a copy of each variable for each class, but are the methods/functions duplicated 5 times in memory, or do each of the tests just point to the same single class codebase? If it duplicated for each class, that would just be a waste of memory.

2
  • 1
    Could you please post code that looks correct? ExampleClass test=new test[5] looks very strange. Jan 3, 2015 at 4:18
  • 3
    Allocating an array does not allocate class instances. Whether using arrays or not, multiple instances of a class all use the same executable code and static data members; only the instance data members (i.e. fields) are given new copies for each instance of the class. If you want a more specific answer than that, post a valid C# code example and explain precisely what you want to know. As it is now, it's very hard to understand for sure what you are asking. Jan 3, 2015 at 4:34

1 Answer 1

14

Every type loaded into an AppDomain will have a Method Table structure that holds every method that type defines, plus the virtual methods derived from parent (typically Object) and the methods defined by any implemented interface.

This Method Table is pointed by every instance of that object. So every instance does not duplicate all the methods defined by that type, but points to this method table structure with a reference.

For example:

 public class MyClass : IDisposable
 {
        private static void MyStaticMethod()
        {
            // ....
        }
        public void MyInstanceMethod()
        {
            // ....
        }
        public void Dispose()
        {
            throw new NotImplementedException();
        }
 }

This MyClass will have a method table including:

  • MyStaticMethod
  • MyInstanceMethod
  • Dispose
  • And other virtual methods derived from System.Object

Have a look at nice diagram of method table:

Method Table Diagram

You can check the whole article about method tables here

1
  • 1
    Is this method table ever unloaded from memory? e.g. if the garbage collector has cleaned all instances of a certain type - will that type's method table still stick in memory?
    – BornToCode
    Aug 10, 2016 at 8:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.