Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning instance created in 'using' statement

Tags:

c#

using

If I have this method:

public StreamReader GetResourceStream(string filename)
{
    using (Stream stream = this.GetType().Assembly.GetManifestResourceStream(filename))
    using (StreamReader sr = new StreamReader(stream))
    {
        return sr;
    }
}

When I call it, should I call it this way

StreamReader resource = GetResourceStream("blah.xml");

or this way:

using (StreamReader resource = GetResourceStream("blah.xml"))
{
    // Do stuff
}

If second way, does this means the using (StreamReader sr = new StreamReader(stream)) line is not making any difference by using a using statement?

like image 551
Ahmet Avatar asked Sep 09 '11 22:09

Ahmet


People also ask

What is using () in C#?

The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned. A variable declared with a using declaration is read-only.

What is the use of using statement in C# with example?

The using statement is used to set one or more than one resource. These resources are executed and the resource is released. The statement is also used with database operations. The main goal is to manage resources and release all the resources automatically.

Does using call Dispose C#?

C# provides a special "using" statement to call Dispose method explicitly. using statement gives you a proper way to call the Dispose method on the object. In using statement, we instantiate an object in the statement. At the end of using statement block, it automatically calls the Dispose method.


1 Answers

You should change the method itself not to include a using statement, but then make sure that the calling code uses a using statement:

public StreamReader GetResourceStream(string filename)
{
    return new StreamReader(GetType().Assembly
                                     .GetManifestResourceStream(filename));
}

using (StreamReader resource = GetResourceStream("blah.xml"))
{
    // Do stuff
}

That way it will only dispose of the resource when you've actually used it. Basically the method is giving ownership of the returned resource to the caller. That much isn't too bad - it's reasonably common, even (think of File.OpenText etc).

Where it gets more tricky is when you pass a resource into a method or constructor - should the "called" code take ownership or not? Usually not, but occasionally it's appropriate - for example, the Bitmap(Stream) documentation states that you must keep the stream alive for as long as the bitmap is required. In fact, disposing of the bitmap also disposes of the stream, so you still only have one resource to keep track of... but you do need to know that you mustn't close the stream.

like image 78
Jon Skeet Avatar answered Oct 14 '22 03:10

Jon Skeet