dantex47
dantex47

Reputation: 47

C# turning console output on/off

I am making a C# DLL that analyzes network traffic using SharpPcap. One of the tings I want to implement is togglable console output. The idea is to have a method in my class

public void ConsoleOutputOn(bool outputOn)

that receives true if console output is desired, and false if it is not. I don't know how would I implement that.

In LUA I could write

local dprint2 = function() end
function consoleOutput(outputOn)
  if (outputON == true) then
    dprint2 = function(...)
      print(...)
    end
  else
    dprint2 = function() end
  end
end

If consoleOutput(true) was called, the dprint2 would become print, and each time dprint2 was called the input arguments would be passed to print and printed on console output. If consoleOutput(false) was called than dprint2 would be empty function that did nothing.

I tried to do the same in C#, my class would have private variable "consoleOn", and instead of print I would call

public void ConsoleOuptput(...) {
  if(outputOn) {
    Console.WriteLine(...);
  }
} 

that would check if "consoleOn" is true, and if it is, send arguments to Console.WriteLine().

Problem is that Console.WriteLine() is overloaded 19 times for all kinds of input arguments. Is there even a way to code "if sonsoleOn pass all arguments to Console.WriteLine()". Or is there a better way to make toggleable Console output.

Keep in mind tha I am making DLL. I can't just turn of console completely.

Upvotes: 4

Views: 926

Answers (2)

InBetween
InBetween

Reputation: 32760

Another option is simply wrapping the Console with a toggable class:

public class MyToggableConsole
{
    public bool On { get; }
    public void WriteLine(string message)
    {
        if (!On)
           return;

        Console.WriteLine(msg);
    }

    //Do same for all other `WriteLine` and `Write` overloads you need.
}

Or if it's very local, say one method, you can even consider defining a local Action based on outputOn:

var WriteToOutput = outputOn ? new Action<string>(s => Console.WriteLine(s) : new Action<string>(s => { } );

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062855

One approach I've used quite successfully with this recently is to use a logger instance (probably just TextWriter) that is allowed to be null. Now, the purists might be thinking "null objects are an anti-pattern", but it allows some awesome usage, for example:

log?.WriteLine($"Connection from '{from}' to '{to}', {data.Length} bytes to process...");

which is then basically free if the log instance is null, thanks to the way the short-circuiting is evaluated. And of course, Console.Out is a TextWriter, so if you want to enable console logging:

myApp.Log = Console.Out;

But equally you can log to a file, or a network socket, or anything else - just by changing what you assign to myApp.Log. And if it is null: logging just stops.

Upvotes: 3

Related Questions