In C#, if I want to deterministically clean up non-managed resources, I can use the "using" keyword. But for multiple dependent objects, this ends up nesting further and further:
using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
{
using (BufferedStream bs = new BufferedStream(fs))
{
using (StreamReader sr = new StreamReader(bs))
{
// use sr, and have everything cleaned up when done.
}
}
}
In C++, I'm used to being able to use destructors to do it like this:
{
FileStream fs("c:\file.txt", FileMode.Open);
BufferedStream bs(fs);
StreamReader sr(bs);
// use sr, and have everything cleaned up when done.
}
Is there a better way in C# to do this? Or am I stuck with the multiple levels of nesting?
You could use this syntax to condense things down a bit:
This is one of those rare occasions where not using { } for all blocks makes sense IMHO.
You don't have to nest with multiple usings:
It should be noted that generally when creating stream based off another stream the new stream will close the one being passed in. So, to further reduce your example:
You can put using statements together before the opening braces like so:
http://blogs.msdn.com/ericgu/archive/2004/08/05/209267.aspx
for this example let us assume you have:
a file named 1.xml under c:\
a textbox named textBox1, with the multi-line properties set ON.
The using statement is syntactic sugar that converts to:
You can explicitly call Dispose on your objects, but it won't be as safe, since if one of them throws an exception, the resources won't be freed properly.