Tray13
Tray13

Reputation: 139

Clearing instance of image

Just not sure, if I have class of type Image and want to clear it, is it enough to set its instance to null? Or I need to call its dispose method? Thanks

Upvotes: 1

Views: 661

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500515

You should definitely dispose it. For example, it might have an open file handle which will remain in use until finalization if you just allow the image to be garbage collected. That's just one practical example of a problem - but the best clue that you should dispose of the image is that the class implements IDisposable :)

Note that usually you shouldn't set variables to null - that's rarely required, and adds clutter to the code. You should dispose of disposable objects. Typically that's done in a using statement, unless you're disposing of an instance variable, which would typically be done within your own Dispose method.

Final note: you can't set an instance to null... you can assign the value "null" to a variable, that's all.

Upvotes: 2

Cody Gray
Cody Gray

Reputation: 244742

You need to call its Dispose method. Setting an instance variable to null doesn't do anything useful, and you shouldn't ever need to do this in C#.

In general, the rule is that if an object implements the IDisposable interface, you should call its Dispose method as soon as you are finished with it. This helps to avoid memory leaks for objects that make use of unmanaged resources. The best way to do this is wrapping it in a using statement.

Upvotes: 2

Related Questions