BreakHead
BreakHead

Reputation: 10672

Difference between ObjectOfFoo = null and ObjectOfFoo.Dispose()

I know to use Dispose() the class should be get inherited from IDisposable, but in my application a class is not inheriting IDisposable and if I simply assign null to fooObject will it deallocate the resources?

Thanks!

Upvotes: 1

Views: 191

Answers (2)

Mez
Mez

Reputation: 4726

If an object is your own class and you put a dispose mechanism in it and dispose it instead of assign null value to it, it is better because this will give you more control over memory and performance.

Destroying objects explicitly is not a bad practice at all. The GC does such things for us but the system has to wait as when the object will be out of scope and when to make it ready for Garbage Collection. This may take some time, so it is a good practice to dispose of objects which have become in a useless state.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062905

Assigning to null is usually not helpful (mainly useful if you are releasing a field on an object that will live much longer) - it certainly doesn't force collection. Dispose() is unrelated to collection, and is intended for when you need that. If you don't have any resources that need prompt Dispose() (unmanaged resources, connections, etc) then implementing IDisposable is not necessary.

Leave the GC alone - it will collect efficiently when it chooses, which on "regular" .NET means a generational scheme; short-lived objects are very efficient to collect.

Upvotes: 3

Related Questions