Question

Just wanted to verify I will not have any handle leaks and all.. I have the following method

public static MyObject DoSomething(Stream MyStream)
{
     var br = new BinaryReader(MyStream);
     return DoMoreThings(br);                    
}

I create MyStream outside..is it safe to say that after this function br will safely be collected by GC? I don't explicitly dispose it..

Was it helpful?

Solution

Although it will be collected by the garbage collector eventually, it's a rather bad practice to leave it there uncollected.

You can ensure that it's cleaned up by wrapping it in a using:

using (var br = new BinaryReader(MyStream))
{
    return DoMoreThings(br);
}

The only drawback here is that the using means that it will call br.Dispose, which among other things will close the underlying stream: MyStream in this case. You can prevent that by calling the overloaded constructor, telling it to leave the stream open:

using (var br = new BinaryReader(MyStream, Encoding.UTF8, true))

Replace the Encoding.UTF8 with whatever encoding matches the strings in your file. Encoding.UTF8 is the default used by the constructor that doesn't take an Encoding parameter.

OTHER TIPS

It will be eventually, but you should type it like this instead

using(var br = new BinaryReader(MyStream))
{
     return DoMoreThings(br);
}

Using statement is a syntactic sugar on try..finally block, firing Dispose method. All objects implementing IDisposable interface should be disposed manually.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top