I am relatively new to C#.
I was wondering if there is a difference between this
// style 1
using (Stream stream_dst = File.Create("output.txt"))
using (Stream stream_src = File.OpenRead("input.txt"))
{
stream_src.CopyTo(stream_dst);
}
And the following
// style 2
Stream stream_output = File.Create("output.txt");
Stream stream_input = File.OpenRead("input.txt");
using (Stream stream_dst = stream_output)
using (Stream stream_src = stream_input)
{
stream_src.CopyTo(stream_dst);
}
Does the object being handled inside the using(...)
context have to be instantiated in the using(...)
expression, or can it be instantiated anywhere and still be properly handled and closed at the end?
This:
using (Stream stream_dst = File.Create("output.txt"))
using (Stream stream_src = File.OpenRead("input.txt"))
{
stream_src.CopyTo(stream_dst);
}
is the same as this:
using (Stream stream_dst = File.Create("output.txt"))
{
using (Stream stream_src = File.OpenRead("input.txt"))
{
stream_src.CopyTo(stream_dst);
}
}
Both ensure that if an object is created it will also get disposed.
In this case:
Stream stream_output = File.Create("output.txt");
Stream stream_input = File.OpenRead("input.txt");
using (Stream stream_dst = stream_output)
using (Stream stream_src = stream_input)
{
stream_src.CopyTo(stream_dst);
}
stream_output
will get disposed because you're disposing stream_dst
, and it's the same stream. But if an exception is thrown before that using
block then stream_output
will not get disposed.
A using
block allows us to combine creating/acquiring an object with ensuring its disposal. If the using
block follows creating/acquiring the object then it will still dispose it, but only if no exception is thrown before the using
statement is executed. We wouldn't generally separate the two because combining them is the benefit of using
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With