Quantcast
Viewing latest article 4
Browse Latest Browse All 7

#189 – Memory Management for Stack-Based Objects

When an object is created on the stack, memory is allocated from the stack for that object.

Memory for an object allocated from the stack is not deallocated until the function containing the declaration exits.

        static void Main(string[] args)
        {
            int x = 42;

            SomeMethod();

            // x deallocated when Main() exits
        }

        static void SomeMethod()
        {
            int y = 100;
            int z = 12;
            int sum = y + z;

            // y, z, sum all deallocated when SomeMethod() exits
        }

In practice, you don’t care much when memory for an object is deallocated.  Instead, you care more about the block of code within which you can refer to and use the variable–its scope.


Filed under: Basics Tagged: C#, Stack Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing latest article 4
Browse Latest Browse All 7

Trending Articles