Note that there are some explanatory texts on larger screens.

plurals
  1. POObjectDisposedException when outputting to console
    primarykey
    data
    text
    <p>If I have the following code, I have no runtime or compilation problems:</p> <pre><code>if (ConsoleAppBase.NORMAL_EXIT_CODE == code) { StdOut.WriteLine(msg); } else { StdErr.WriteLine(msg); } </code></pre> <p>However, in trying to make this more concise, I switched to the following code:</p> <pre><code>(ConsoleAppBase.NORMAL_EXIT_CODE == code ? StdOut : StdErr ).WriteLine(msg); </code></pre> <p>When I have this code, I get the following exception at runtime:</p> <blockquote> <p>System.ObjectDisposedException: Cannot write to a closed TextWriter</p> </blockquote> <p>Can you explain why this happens? Can I avoid it and have more concise code like I wanted?</p> <p><strong>Edit:</strong> whoops, sorry, I forgot to note where these mysterious <code>StdOut</code> and <code>StdErr</code> come from:</p> <pre><code>/// &lt;summary&gt; /// Define these so that they can be accessible to unit tests so that /// a different TextWriter instance can be used for capturing output /// for verification. /// &lt;/summary&gt; internal static TextWriter StdOut = Console.Out; internal static TextWriter StdErr = Console.Error; </code></pre> <p><strong>Update:</strong> hm, I just got the same exception with the original, lengthy code, so apparently something else is awry. I'll check what my test cases are doing.</p> <p><strong>Update again:</strong> turns out in my tests I was rerouting standard out but not standard error, but then I did try to write to standard error and it wigged out. My fix:</p> <pre><code>var standardOut = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true }; Console.SetOut(standardOut); // Added this: var standardError = new StreamWriter(Console.OpenStandardError()) { AutoFlush = true }; Console.SetError(standardError); </code></pre> <p>I'm marking <a href="https://stackoverflow.com/questions/2907714/objectdisposedexception-when-outputting-to-console/2907756#2907756">ChaosPandion's answer</a> as the correct one since he correctly identified my test as being screwy.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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