Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory allocation of interface

I know interface cannot be instantiated, but if we assign it to an object, could anyone please explain how the memory gets allocated to it. For ex:

ITest obj = (ITest) new TestClass1();  //TestClass1 is a class which implements ITest
obj.MethodsDefinedInInterface();

Does ITest converts to object to save properties and methods of TestClass1.

like image 700
Sunny Avatar asked Dec 06 '22 10:12

Sunny


2 Answers

I'm not sure exactly what you mean by 'allocation'. The following statement makes two seperate 'allocations':

TestClass1 test = new TestClass1();

First is the new TestClass1() statement which allocates sizeof(TestClass1) on the heap. Second, the assignment of the address of the heap allocation is stored in the variable test, which is allocated on the stack as sizeof(object *) (i.e. IntPtr.Size, or 32/64 bits based on the hardware+OS+software running).

The following statement is EXACTLY the same in 'allocations':

ITest test = new TestClass1();

The only difference between the two is the methods available to be called on the variable test.

Note: This is NOT true with a structure that implements an interface. Interfaces must be a reference type, and as you know, structs are not. This is called boxing in .NET and allows a struct to be referenced as if it were a reference type by first placing a copy of the struct on the heap.

So we now re-evaluate the statement:

TestSTRUCT1 test2 = new TestSTRUCT1();

This 'allocates' sizeof(TestSTRUCT1) on the stack at the named variable test2. (Not sure what the impact of the assignment to new TestSTRUCT1() is, it may create an additional stack copy but that should be removed immediately after the assignment.

If we then assign this value to an interface:

ITest test3 = test2;

We have now made two more allocations. First the structure is copied to the heap. Then the address of that heap-resident structure is placed in a newly 'allocated' variable test3 (on the stack).

like image 74
csharptest.net Avatar answered Dec 10 '22 03:12

csharptest.net


It should be similar to:

TestClass1 test = new TestClass1();  
ITest obj = (ITest) test;
obj.MethodsDefinedInInterface();

Which, I think, answers your question.

like image 38
Andrei Avatar answered Dec 10 '22 03:12

Andrei