Do I need to implement Dispose() ?
-
I have created a class which when instantiated, creates a SQL connection, SQL command, etc. By repeatedly calling some methods it processes data using that one connection and SQL command. When I'm done with this object, shouldn't I close/dispose of my SQL connection and command? Should I do this by implementing Dispose() ? Or Should I create a method within my class called,"CleanUp" and just release the SQL connection and command there. Also, I have a few Dictionaries and Lists in this class; should I ".Clear" them also ? Maybe I should just set "myObject = Nothing" in my calling application? Your guidance is appreciated.
-
I have created a class which when instantiated, creates a SQL connection, SQL command, etc. By repeatedly calling some methods it processes data using that one connection and SQL command. When I'm done with this object, shouldn't I close/dispose of my SQL connection and command? Should I do this by implementing Dispose() ? Or Should I create a method within my class called,"CleanUp" and just release the SQL connection and command there. Also, I have a few Dictionaries and Lists in this class; should I ".Clear" them also ? Maybe I should just set "myObject = Nothing" in my calling application? Your guidance is appreciated.
If your class owns references to disposable objects, it should implement
IDisposable
to dispose of those references. Providing a public method with a different name has no benefit; you won't be able to wrap your class in aUsing
block, and developers using your class might not even realise that they have to call yourSpecialSnowflakeCleanUp
method when they've finished with an instance of your class. If your class implementsIDispoable
, it's a clear indication that it requires clean-up. There's no need to clear collections or references to managed objects; you only need to worry about unmanaged references and disposable objects. Implementing IDisposable and the Dispose Pattern Properly[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
-
If your class owns references to disposable objects, it should implement
IDisposable
to dispose of those references. Providing a public method with a different name has no benefit; you won't be able to wrap your class in aUsing
block, and developers using your class might not even realise that they have to call yourSpecialSnowflakeCleanUp
method when they've finished with an instance of your class. If your class implementsIDispoable
, it's a clear indication that it requires clean-up. There's no need to clear collections or references to managed objects; you only need to worry about unmanaged references and disposable objects. Implementing IDisposable and the Dispose Pattern Properly[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
Hmmm ... Based on your suggestions, I am going to refactory my code.