Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many methods in a class will be created in memory when an object is created in C#? [duplicate]

Tags:

c#

.net

oop

I have a some small doubt with classes and objects.

In a class I have 10 to 20 methods, (shared below)

    public class tstCls
    {
       public void a1()
        { }
        void a2()
        { }
        void a3()
        { }
        void a4()
        { }
        void a5()
        { }
        void a6()
        { }
        void a7()
        { }
        void a8()
        { }
        void a9()
        { }
    }

When creating a object for the above class. How many methods will be stored in memory? Only the calling method or all the methods.

 static void Main(string[] args)
    {
        tstCls objcls = new tstCls();
        objcls.a1();
    }

Can you please help me on the above scenario.

like image 698
Anjali Avatar asked Aug 12 '16 05:08

Anjali


2 Answers

None.

The methods are not created in memory when you instantiate an object, only the fields and properties are.

The assembly that contains the methods is loaded whenever any part of the assembly is referenced.

Methods get compiled into memory only when they are called. The JIT (Just-In-Time compiler) turns the methods from IL into machine code at that moment in time.

like image 60
Enigmativity Avatar answered Oct 02 '22 18:10

Enigmativity


For an instance only one method will be created.

You can refer this artilce: Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects

Each class and interface, when loaded into an AppDomain, will be represented in memory by a MethodTable data structure. This is a result of the class-loading activity before the first instance of the object is ever created. While ObjectInstance represents the state, MethodTable represents the behavior. MethodTable binds the object instance to the language compiler-generated memory-mapped metadata structures through EEClass. The information in the MethodTable and the data structures hanging off it can be accessed from managed code through System.Type. A pointer to the MethodTable can be acquired even in managed code through the Type.RuntimeTypeHandle property. TypeHandle, which is contained in the ObjectInstance, points to an offset from the beginning of the MethodTable. This offset is 12 bytes by default and contains GC information which we will not discuss here.

enter image description here

like image 27
Rahul Tripathi Avatar answered Oct 02 '22 18:10

Rahul Tripathi