29 Jan 2024




Intermediate

Consider a scenario where we have a Person class representing individuals with basic attributes like name and age. We'll create instances of this class and observe how memory allocation works:

using System;

class Program
{
    static void Main(string[] args)
    {
        // Stack allocation
        int a = 10;
        int b = 20;

        // Heap allocation
        Person person1 = new Person("Alice", 30);
        Person person2 = new Person("Bob", 25);

        Console.WriteLine($"Person 1: {person1.Name}, Age: {person1.Age}");
        Console.WriteLine($"Person 2: {person2.Name}, Age: {person2.Age}");

        Console.ReadLine();
    }
}

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

In this example:

  • We have two local variables a and b allocated on the stack within the Main() method.
  • We create two instances of the Person class, person1 and person2, using the new keyword. These instances are allocated on the heap.
  • Each Person object contains a Name and an Age property.

Now, let's understand how memory allocation works:

stack-heap-example

  • a and b are variables stored on the stack.
  • person1 and person2 are references stored on the stack, pointing to Person objects in the heap.
  • Each Person object contains memory for its properties (Name and Age).

This diagram illustrates how stack and heap memory are used in this example. The stack stores references to the heap-allocated Person objects, while the heap stores the actual object data.

c-sharp
stack
heap
example