Thursday, 14 February 2013

The object which is created can also be destroyed by assigning null to it. Once we assigned null to an object the memory which is allocated for object is marked as unused and cannot be accessed anymore. To test this rewrite the code under Main method of First class as following:

Note: The memory which is marked as unread will be deallocated by the Garbage Collector whenever it comes into a picture for deallocation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpConsole
{
    class First
    {
        int x = 100;
        static void Main()
        {
            First obj = new First();
            Console.WriteLine(obj.x);  // Prints the value here
            obj = null;
            Console.WriteLine(obj.x);  // Error occurs here
            Console.ReadLine();
        }
     }
}

No comments:

Post a Comment