Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Calling a method on a disposed object will throw <code>ObjectDisposedException</code>. E.g.:</p> <pre><code>var textWriter = Console.Error; textWriter.Dispose(); textWriter.WriteLine("Test"); </code></pre> <p>The last line should throw an exception. Except it doesn't always to that.</p> <p>If you peruse the BCL source code you can see that <code>Console</code> either uses a <code>StreamWriter</code> (really a synchronized stream writer) that is hooked up to either a "real" stream (e.g. the console error stream) or if that is not available to <code>StreamWriter.Null</code>.</p> <p>The "real" <code>StreamWriter</code> is constructed in a special way so that it is not closeable. This means that even if you close it (or dispose it) it just continues to function as expected.</p> <p>So if you have a "real" console stream you can close <code>Console.Error</code> as many times as you want without closing the underlying stream. Also you wont get any <code>ObjectDisposedException</code>.</p> <p>If there is no "real" stream attached to <code>Console.Error</code> closing the <code>StreamWriter</code> will close the underlying stream (in this case <code>Stream.Null</code>) which doesn't exhibit the special non-closeable behavior, and if you try to use the <code>StreamWriter</code> later you will get an <code>ObjectDisposedException</code>.</p> <p><strong>The bottom line is that you can get a <code>ObjectDisposedException</code> if you close a console stream writer prematurely in an application that doesn't have a real console stream.</strong></p> <p>The information above also applies to <code>Console.Out</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload