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
aandballocated on the stack within theMain()method. - We create two instances of the
Personclass,person1andperson2, using thenewkeyword. These instances are allocated on the heap. - Each
Personobject contains aNameand anAgeproperty.
Now, let's understand how memory allocation works:

aandbare variables stored on the stack.person1andperson2are references stored on the stack, pointing toPersonobjects in the heap.- Each
Personobject contains memory for its properties (NameandAge).
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.