Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 219
  • Last Modified:

Dispose

When I write classes in C# then implement them as follows:

ETrainingDemo.Classes.NewsLetterRecipient objRecipient = new ETrainingDemo.Classes.NewsLetterRecipient();

objRecipient.Firstname = Firstname.Text;
objRecipient.Surname = Surname.Text;
objRecipient.Email = Email.Text;
objRecipient.Add()

If I want to kill the object straight away rather than relying on the garbage collector, what is the best way to do this.  Is there a command like Set object = Nothing?  Should I build dispose code into my class, should I inherit a Dispose Interface?

Any thoughts, ideas please?

Thanks

Dave
0
daveamour
Asked:
daveamour
  • 2
  • 2
1 Solution
 
iamtsubasaCommented:
Your class seems to only contain intrinsic data types (like string, int, ...).  If so, I suggest you let the garbage collector do the work.  In this case, all you have to do is to set objRecipient to null: "objRecipient = null;".

If you have more complicated members in your class (eg. file class, handles, ...), then you probably want to inherit and implement the IDisposable interface.  The method that you will have to implement is Dispose().  Here you will close the file and clean up everything.  You might also want to override your destructor to call the Dispose method, too.

If you decide to clean up everything yourself, you can call GC.SuppressFinalize() so the garbage collector won't have to waste CPU cycles on trying to do the work already done.

Hope this helps.
0
 
daveamourAuthor Commented:
Thanks, that all makes sense and is a great help.  How do I overide the destructor though?  I'm not really sure what this means.

Thanks

Dave
0
 
iamtsubasaCommented:
Sorry for confusing...
Not really overriding it.  Just implement the destructor like this would do it:

~NewsLetterRecipient()
{
    Dispose();
}

Regards.
0
 
daveamourAuthor Commented:
Ok, thanks very much :)
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now