Let’s say I have a class that has a MyCustomDatabaseAccess as a data member. MyCustomDatabaseAccess has a Dispose() method. MyCustomDatabaseAccess is the middleware class that accesses the database.
public class MyClass {
private MyCustomDatabaseAccess db_access;
}
Does MyClass need to implement IDisposable interface?
My solution right now is to have do something like this:
public class MyClass {
private MyCustomDatabaseAccess db_access;
public void GetDBResults () {
db_access = new MyCustomDatabaseAccess();
DataTable dt = db_access.ExecuteStoredProc(param1, param2, etc..);
//do stuff with results
db_access.Dispose();
}
}
From what I read on MSDN, another way to make sure that this object is disposed of properly would be to have MyClass implement IDisposable interface, then implement a Dispose() function, then call it in the class that calls an object of MyClass.
see this for more info
http://www.devx.com/dotnet/Article/33167/0/page/3
Which way is preferable and why?
thanks!
I think you just need to ensure your objects are disposed.
if you are doing this in your method, even if there is an unexpected error, then I think you are ok. If you hold on to unmanaged resources in your class then implementing IDisposable is a way to ensure that you get a chance to dispose resources when your object is finalized, or to give your users a way to dispose of the resources explicitly.
If you are only creating and using the resources in a method and not holding references in the class then as long as you are ensuring they are disposed in the method (either by doing it manually , or more easily, by wrapping then in a using block), then you should be ok I think.