0

The code looks like this.

public class clsMisc : IDisposable {
  List<clsEmployee> lst = new List<clsEmployee>();

  void Add(){
     lst.Add(obj);
     //Adding to it list here
  }

  public void Dispose()
  {
    lst = null;
  }

}

The above class is called like this,

Using( clsMisc obj = new clsMisc()){
 //Here goes the code
}

once it comes out of the using scope, the dispose method in the clsMisc s called and in that we assigned null.

Will the values stored in memory ( existing records of clsEmployee in the list) will be released and it will assign new value or it will create a new instance of List and assign the null value ?

I couldn't understand the behaviour since i am very new.

Can someone please guide me in this ?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
shanmugharaj
  • 3,814
  • 7
  • 42
  • 70
  • 1.You don't need to set `lst` to `null`. 2.What exactly is your question? Does the object gets GC'd after the using statement completes? or different? – Sriram Sakthivel Jan 14 '15 at 06:07
  • After setting setting to null what eaxctly will happen ? – shanmugharaj Jan 14 '15 at 06:08
  • Nothing will happen immediately. But if that happens to be the only reference to instance which you set to null. Which means that there are no more managed references to the object, it is eligible to garbage collection. GC will collect it when garbage collection triggerrs. – Sriram Sakthivel Jan 14 '15 at 06:11
  • @SriramSakthivel Thanks for reply. I got the point. So probably no big benefit i will get because of using IDisposable in the above scenario right ? – shanmugharaj Jan 14 '15 at 06:13
  • I've marked the question as duplicate. Refer the suggested duplicate question link right above your question. It will answer you in great detail. Thanks. – Sriram Sakthivel Jan 14 '15 at 06:15
  • It is a good practice though to do some memory cleanup when implementing utility classes especially and not simple models carrying data properties. Especially useful when you want to immediately use and dispose resources with a using() {} block. – George Taskos Jan 14 '15 at 06:16
  • 1
    IDisposable and the `using` block have nothing to do with memory. They have to do with resource utilization. – John Saunders Jan 14 '15 at 06:16

1 Answers1

2

You shouldnt have to worry about it at all as the collector is rather smart and because it is a managed language, you should really let it be.

The collector will decide when it needs to do a cleanup so it is not guaranteed when it will do its work.

BUT if you are dead set on forcing a collection, you can call GC.Collect

David Pilkington
  • 13,528
  • 3
  • 41
  • 73