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?
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.
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.
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.
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.
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