Is there a way to dispose method variables without using try-finally block in C# 2010 (.Net 4)?
The story:
I have few files handler methods. Each handler (method) can abort in the middle of execution.
I like to dispose all method’s object before exiting the method.
The option to compose dispose method for each handler is not an option.
Thank you
This demonstrate the general idea:
`public static class Comparison
{
private static bool CompareXmls(…)
{
//has 7 object to be disposed in 3 exit points acordding to 4 conditions
//General method flow:
//1. init part of the object
//2. if(!<condition1>)
//disposed objects
//exit method
//3. perform some actions
//4. init some of the other objects
//2. if(!<condition2>)
//disposed objects
//exit method
//and so on...
}
private static bool CompareJpgs(...)
{
//has 12 object to be disposed in 10 exit points acordding to 4 conditions
}
private static bool CompareBitMaps(...)
{
//has 5 object to be disposed in 3 exit points acordding to 4 conditions
}
private static bool CompareTxts(...)
{
//has 12 object to be disposed in 10 exit points acordding to 4 conditions
}
}`
I have another 7 comparison methods
using? Refer here for the full description on how and why to use http://msdn.microsoft.com/en-us/library/yh598w02(v=VS.100).aspx. A sample would beafter exiting from the
usingblock, all disposable objects declared in its header will be disposed.If your disposable objects are of different types, you can use nested
usings: