03 November 2012

.net c# memory allocation for reference types

One of my buddy who also works on .NET attended an interview recently. In one of the rounds of technical discussion, he was asked an interesting question on memory allocation for reference types.

What is the output of the below program?

namespace MemoryAddressForReferenceTypeParameter
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee employeeObject = new Employee();
            Process(employeeObject);
        }
        private static void Process(Employee employeeObject)
        {
            // Set null to reference type parameter
            employeeObject = null;
        }
    }
    public class Employee
    {
    }
}

Looking at the code above I said to my friend that its throws System.NullReferenceException. But actually it doesn't throws any exception and the program writes "MemoryAllocationForReferenceTypes.Employee" to the console and gracefully exists.

For a moment I and my friend were wondering what's happening. Later we realized the fact that, even when reference type variable is passed to a method, the method argument will is altogether a different variable, but its also pointing to the same memory location where employee object is stored.

The analogy:

  1. Setting null to the method argument inside the Process() method, just removed the one more reference created to the memory location where employee object is stored on the heap.
  2. But the original employee object is still there on the memory intact and employee variable in the Main method still pointing the same memory location where employee object is stored.
  3. Hence ToString() method doesn't throw System.NullReferenceException and it prints the Employee class full name which is expected out the default ToString() method implementation.

But we didn't stop here. And used the ref keyword while passing the parameter value to the Process() method.

namespace MemoryAddressForReferenceTypeParameter
{
    class Program
    {
        static void Main(string[] args)
        {
            Employee employeeObject = new Employee();
            Process(ref employeeObject);
        }

        // Now used ref keyword while passing the parameter
        private static void Process(ref Employee employeeObject)
        {
            // Set null to reference type parameter
            employeeObject = null;
        }
    }
    public class Employee
    {
    }
}

Since ref keyword is used while passing the value to the Process() method, it doesn't create a different variable to point to the same memory location where employee object is stored and hence setting the null to the employee variable will reflect the employee variable present in the Main() method as well. Now, the employee object is null and it throws the System.NullReferenceException.

No comments:

Post a Comment