Click here to Skip to main content
15,903,203 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I had used destructor in program like this

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace destructors
{
    class Program
    {
        int i = 5;
        public Program()
        {
            Console.WriteLine("Object created");
        }
        ~Program()
        {
            Console.WriteLine("Object destroyed");
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            Console.WriteLine(p.i);
            p = null;
            GC.Collect();
            Console.ReadLine();
        }
    }
}



in above program i had used GC.collect for destroy the object but whenever assign

p=null then p object memory deallocate why should use specifically GC.collect().what

is purpose GC.collect().is it mandatory if p=null use in program.

Thank u.

help me.

What I have tried:

in above program i had used GC.collect for destroy the object but whenever assign

p=null then p object memory deallocate why should use specifically GC.collect().what

is purpose GC.collect().is it mandatory if p=null use in program.
Posted
Updated 6-Mar-18 8:39am

You normally never need to call GC.Collect().

It's only use is if you REALLY know what you're doing, why you're doing it, the consequences of calling it, and usually because of memory constraints your code is placing on the system, which is exceedingly rare.

It's use in the above example is just for a demonstration of object lifetime. It's not required in normal code.
 
Share this answer
 
1) p=null statement doesn't de-allocates the object memory. Once this statement is executed p reference no more points to the Program class object it was pointing earlier.

2) De allocation will happen or I say Memory occupied by Program class object in the heap will be released when GC is called next time.

And GC.Collect will make point 2 happen immediately.

Please correct me if I am wrong any where. Hope this helps. Enjoy learning :)
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900