Memory management for a class [closed]
-
27-09-2019 - |
Question
in the following code, How - in terms of memory management - is class A
allocated and deallocated in .NET (C#).
class A
{
public static m1(int x, int y)
{
int x, y;
return x+y;
}
int m2(int p, int q)
{
int p, int q;
return p+q;
}
int x=10;
int y;
const int x=10;
readOnly y=20;
public int x
{
get {y}
set {y=value}
}
}
class B
{
A a=new A(); // what happens when initializing class A;
}
Note: that the usage of class B
could be either the entry point of the program, or an object instance, but the scope here is on memory management and allocation of the instance of class A
.
Solution
The line you describes allocates a single instance of A
on the heap when you create a new instance of B
. So,
B b = new B();
will allocate two objects: one B
with the direct call and one A
as part of constructing the B
.
The line itself does nothing until you create an instance of B
.
A
seems to have three fields which are not reference fields, so it does not create new objects on the heap but are part of the A
instance.
That's roughly all the memory that's allocated in this example.
EDIT:
For purposes of greater clarity - A reference link to an article explaining Stack and Heap, and Memory Allocation considerations: http://www.simple-talk.com/dotnet/.net-framework/.net-memory-management-basics/
OTHER TIPS
When you create an instance of B, the memory is allocated for 1 object with one field of reference type ("A"). Right after that new instance of A is created which causes allocation of memory for object with two "int" fields ("x", "y") and with one field of TYPE IS UNKNOWN type.