user3310334
user3310334

Reputation:

block console output for method call

I am doing something like

interface ICalculable
{
    public int Calculate(int input);
}

BigMethod(ICalculable calculable)
{
    Console.Write("Sequence:");
    for (int i = 0; i < 3; i++)
    {
        int result = calculable.Calculate(i);
        Console.Write($" {i}:{result}");
    }
}

Any code running inside of a ICalculable#Calculate should not be able to write to the console.

I don't want the ICalculable that is passed to BigMethod to be able to interrupt BigMethod's console output, even if I pass an instance of

class MyCalculable : ICalculable
{
    public int Calculate(int input)
    {
        Console.Write("ruin output");
        return 0;
    }
}

The output seen at the console should be

Sequence: 0:0 1:0 2:0

BigMethod should somehow be able to mute its call to Calculate.

Is there a way to do that?


I already thought of using a StringBuilder but I want BigMethod's output to be streamable.

Upvotes: 0

Views: 150

Answers (1)

TheGeneral
TheGeneral

Reputation: 81523

You can use Console.SetOut, and Console.Out

public static void Main()
{
   Console.Write("Hello ");

   // current output
   var current = Console.Out;

   // change the output to somewhere else
   Console.SetOut(new StreamWriter(Stream.Null));

   Run();

   // revert back
   Console.SetOut(current);

   Console.WriteLine("there");
}

private static void Run()
{
   Console.Write("Doctor, please keep touching me ");
}

Output

Hello there

However, this seems a little fishy / XY and prone to outrageously weird results if you are threading.

Upvotes: 1

Related Questions