Pedro77
Pedro77

Reputation: 5294

How to check if Console.Out was set using my TextWriter

I'm changing the Console out to a custom TextWriterclass (TextBoxStreamWriter). I want to check if the Console.Out was set using my writer instance or not (because other class may have changed it, etc).

Sample:

// "TextBoxStreamWriter : TextWriter" is a custom class that writes to a textbox...
TextBoxStreamWriter myWriter = new TextBoxStreamWriter(someTextBoxInstance);
Console.SetOut(myWriter);
bool check = Console.Out == myWriter;
// But check is false! I need to know if .Out was set from my custom class or not.

Upvotes: 0

Views: 188

Answers (2)

Victor Hurdugaci
Victor Hurdugaci

Reputation: 28425

That's expected, look at the Console.SetOut source code: http://referencesource.microsoft.com/#mscorlib/system/console.cs,2d6029756ecc3409 . It wraps your text writer in a SyncTextWriter.

I think you have to use reflection to see the wrapped type.

Upvotes: 0

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73472

Console.SetOut will wrap your myWriter in a another TextWriter to make it thread safe by wrapping all the calls in a lock. This is the reason why you get false when you check Console.Out == myWriter;

You need some reflection code to check it, because the wrapping TextWriter is internal. It is named as SyncTextWriter.

You can refer the source here for more information.

Upvotes: 1

Related Questions