Arne Vajhøj said:
Sure it will , try this...
.....
StreamReader sr = null;
using ( sr = new StreamReader("canread.cs"))
{
.....
} // sr Disposed here.
if(sr != null && sr.BaseStream.CanRead)
Console.WriteLine("Stream can still be read from");
It will throw...
Unhandled Exception: System.NullReferenceException: Object reference not set to
an instance of an object.
sw.Dispose();
does not by magic set sw to null.
The sw != null test is rather meaningless in the context
of the subject.
I have some doubts whether sw.BaseStream != null is sufficient. It
is based on the assumption that Dispose actually sets BaseStream
to null. Current implementation does. But if a future implementation
just call Dispose and do not set it to null, then the code will break.
I think sw.BaseStream.CanWrite is a nice extra check to have.
Note, that future implementations can hardly change this behavior (which I don't rely upon
anyway!), without introducing a breaking change, if you look at the current implementation
of the FCL, setting BaseStream to null is done especially to guard themselves against
further access of the underlying stream.
Anyway, currently, BaseStream is effectively set to null in the SW or SR's Dispose method ,
so, sw.BaseStream.CanWrite will throw a NullReferenceException after the sw is disposed, so
what's the deal, handle a NullReferenceException or an bjectDisposedException?
I prefer the latter, the first one is too confusing, you don't expect this, right?.
That's why I assume "A disposed object being a dead object", I won't use it any longer.
Willy.