What is the object life cycle for an object in .NET?
From what I understand it is:
Here is an example class that uses all the information available in the articles provided here. I have already spent hours testing things out, and this is what works best for me.
/*********************************
* Author: Theofanis Pantelides *
* Date: 23 Jun 2009 *
*********************************/
using System;
using System.IO;
public class MyClass : IDisposable
{
String oFile;
Stream oStream;
public MyClass(String _File)
{
oStream = File.OpenRead(oFile = _File);
// Initialize
}
~MyClass()
{
this.Dispose();
// Destruct
}
public void doSomething()
{
// do Whatever it is you are trying to do
}
#region IDisposable Members
///
/// Dispose all resources used by instance of class
/// and update Garbage Collector information
///
public void Dispose()
{
if (oStream != null)
{
oStream.Dispose(); // Dispose using built in functions
GC.SuppressFinalize(oStream); // No need for Garbage Collector
}
oStream = null; // Nullify it.
}
#endregion
}
Usage:
using(MyClass mc = new MyClass(@"c:\temp\somefile.txt"))
{
mc.doSomething();
}
You can even use the same declaration twice as it does not exist outside the 'using'.
using(MyClass mc = new MyClass(@"c:\temp\somefile.txt"))
{
mc.doSomething();
}
using(MyClass mc = new MyClass(@"c:\temp\somefile.txt"))
{
mc.doSomething();
}