I have two classes, say class MyFirstClass and MyAnotherClass , MyAnotherClass is implementing IDiposable interface.
public class MyFirstClass
{
public string xyz{get;set;} ..... and so on
}
public class MyAnotherClass : IDisposable
{
private readonly MyFirstClass objFc = new MyFirstClass();
public static void MyStaticMethod()
{
var objOfFirstClass = new MyFirstClass();
// something with above object
}
public void MyNonStaticMethod()
{
// do something with objFc
}
#region Implementation of IDisposable
.... my implementations
#endregion
}
Now I have one more class where I am calling MyAnotherClass , something like this
using(var anotherObj = new MyAnotherClass())
{
// call both static and non static methods here, just for sake of example.
// some pretty cool stuffs goes here... :)
}
So I would like to know, should I worry about the cleanup scenario of my objects? Also, what will happen to my ObjFC (inside non static) and the objOfFirstClass (inside static).
AFAIK, using will take care of everything…but i need to know more…
objOfFirstClassis a local variable in a method. It will be eligible for garbage collection once the method is exited. It won’t be disposed as such because it doesn’t implementIDisposable.objFcwill be eligible for garbage collection when its parent object goes out of scope. Again, this is nothing to do with disposing it.Dispose/IDisposableis used when there is clean up other than simple memory management to be done. The CLR handles cleaning up the memory for you using garbage collection.usingis a nice way of ensuring that an object implementingIDisposablehas itsDisposemethod called when you have finished with it – but if all you are after is memory management, you don’t need to use it.