In C#, if a class, such as a manager class, does not have resources, is there any benefit to having it : IDisposable
?
Simple example:
public interface IBoxManager { int addBox(Box b); } public class BoxManager : IBoxManager { public int addBox(Box b) { using(dataContext db = new dataContext()){ db.Boxes.add(b); db.SaveChanges(); } return b.id; } }
Will there be any benefit in memory use when using BoxManager if it also implements IDisposable? public class BoxManager : IBoxManager , IDisposable
For example:
BoxManager bm = new BoxManager(); bm.add(myBox); bm.dispose();//is there benefit to doing this?
If your class creates unmanaged resources, then you can implement IDisposable so that these resources will be cleaned up properly when the object is disposed of. You override Dispose and release them there.
You should implement IDisposable when your class holds resources that you want to release when you are finished using them. Show activity on this post. When your class contains unmanaged objects, resources, opened files or database objects, you need to implement IDisposable .
You never know when the garbage collector will collect your object. You don't even know if it even will (unlike using delete in C++, which is deterministic). So IDisposable is there for deterministically releasing unneeded references (and releasing unmanaged resources).
The documentation of Object. To ensure deterministic release of resources for instances of your class, implement a Close method or provide a IDisposable. Dispose implementation. This is the virtue of using Dispose to cleanup unmanaged resources; you get to know, and control, when unmanaged resource are cleaned up.
There are only 2 reasons for implementing IDisposable
on a type
IDisposable
If neither of these are true then don't implement IDisposable
EDIT
Several people have mentioned that IDisposable
is a nice way to implement begin / end or bookended operations. While that's not the original intent of IDisposable
it does provide for a very nice pattern.
class Operation { class Helper : IDisposable { internal Operation Operation; public void Dispose() { Operation.EndOperation(); } } public IDisposable BeginOperation() { ... return new Helper() { Operation = this }; } private void EndOperation() { ... } }
Note: Another interesting way to implement this pattern is with lambdas. Instead of giving an IDisposable
back to the user and hoping they don't forget to call Dispose
have them give you a lambda in which they can execute the operation and you close out the operation
public void BeginOperation(Action action) { BeginOperationCore(); try { action(); } finally { EndOperation(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With