Saturday 24 August 2019

c# - Object allocation

This is a theoretical question and I want to test my understanding of object allocation in memory. We know that objects are allocated on the managed heap while the value types are allocated on stack memory, reason being the CLR will dynamically create the required object memory on managed heap, while the value types being of fixed length can be maintained on a stack. And the object references are also stored on stack.



Now consider the scenario here:



public class MyClass 
{
public int t;

public string str;
}

public class Program {

public static void Main()
{
int a = 5;

MyClass obj = new MyClass();


obj.t = 7;

obj.str = "any string";

Console.WriteLine(obj.str);

}
}



My questions are the following:




  1. In this scenario, how will the stack and heap look like ?

  2. The class MyClass contains some value type, so where will these be allocated ?

  3. The value types for Main are also within the class Program, so where will these be allocated ?

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...