Memory Management in C#
C# automatically manages memory so that developers are freed to worry about memory management. In early days of C and C++, manual memory management requires us to write code to allocate and de-allocate memory blocks.
Automatic memory management does not only increase code quality but it also increases productivity. Developers focus on functional aspects rather than internals.
Take following example of Stack class,
public class Stack
{
private Node first = null;
public bool Empty
{
get
{
return (first == null);
}
}
public object Pop()
{
if (first == null)
throw new Exception(“Can’t Pop from an empty Stack.”);
else
{
object temp = first.Value;
first = first.Next;
return temp;
}
}
public void Push(object o)
{
first = new Node(o, first);
}
class Node
{
public Node Next;
public object Value;
public Node(object value) : this(value, null) { }
public Node(object value, Node next)
{
Next = next;
Value = value;
}
}
}
Here, Node instances are created in Push method and GC collects them, when they are not referenced.
Another example would be,
class Test
{
static void Main()
{
Stack s = new Stack();
for (int i = 0; i < 10; i++)
s.Push(i);
s = null;
}
}
Here, we create an instance of Stack 10 times and then assign null value. As soon as instance is assigned with null value, it’s eligible for garbage collection (GC). Although, it’s unpredictable when garbage collector will run, but as a C# developer we don’t need to worry about it.
