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
andb
allocated on the stack within theMain()
method. - We create two instances of the
Person
class,person1
andperson2
, using thenew
keyword. These instances are allocated on the heap. - Each
Person
object contains aName
and anAge
property.
Now, let's understand how memory allocation works:
a
andb
are variables stored on the stack.person1
andperson2
are references stored on the stack, pointing toPerson
objects in the heap.- Each
Person
object contains memory for its properties (Name
andAge
).
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.