Is it possible to use using syntax to trigger all objects that implement IDisposable interface call the corresponding Dispose() method?
For example, if the objects of ObjectOne and ObjectTwo exist in the section of interest, can we make it the way so that the Dispose() method of both objects will be called automatically. As the example shown, I knew how to do it for one Class type, but I don't know how to do this kind of trick for more than one Class type. Because the following syntax is not allowed in C#.
// This is not a valid C# statement
using( ObjectOne one = new ObjectOne();
OjbectTwo two = new ObjectTwo() )
{
...
// hopefully, the Dispose methods of both **one** and **two** will be called.
}
A concrete example to illustrate how to trigger the auto-calling Dispose method for just one class type.
namespace ConsoleApplication1
{
class ObjectOne : IDisposable
{
public string ObjectName { get; set; }
public ObjectOne() : this("Empty") { }
public ObjectOne(string objName)
{
ObjectName = objName;
}
public void Dispose()
{
Console.WriteLine("ObjectOne.Dispose " + ObjectName);
}
}
class ObjectTwo : IDisposable
{
public string ObjectTwoName { get; set; }
public ObjectTwo() { }
public ObjectTwo(string objName)
{
ObjectTwoName = objName;
}
public void Dispose()
{
Console.WriteLine("ObjectTwo.Dispose " + ObjectTwoName);
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("before");
// make sure that the Dispose method of object one1 and one2 is called
using (ObjectOne one1 = new ObjectOne(),
one2 = new ObjectOne()
)
{
// section of interest
Console.WriteLine("middle");
}
Console.WriteLine("after");
Console.ReadLine();
}
}
}
Thank you.