Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does object instantiation have to occur inside using block expression?

Tags:

c#

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?

Remark: The question is a pedagogical one. Not whether or not a person should, but whether or not a person can. And in particular, if there are differences between the two methods. Please keep this in mind.

like image 589
AlanSTACK Avatar asked Jan 01 '23 22:01

AlanSTACK


1 Answers

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.

like image 124
Scott Hannen Avatar answered Jan 26 '23 01:01

Scott Hannen