How to write schedules in console entries without repeating too much code

0

I want all Console.WriteLine to be this way when it is sent to the Console:

  

[10: 38: 12: 758] - Message typed in WriteLine

Well I've done a part that is this:

private static DateTime data = DateTime.Now;
Console.WriteLine("[{0}]", data.ToString("HH:mm:ss:fff"));

However, I want to write several messages, and in the case I would have to enter this code a lot of times, I wanted it to be something like this:

"CW (" Message ")" and already appeared "DateTime now" in the format I mentioned above, how can I do this?

I made this code:

public void msg(string mensagem)
{
    mensagem = "";
    Console.WriteLine("[{0}], [{1}]", data.ToString("HH:mm:ss:fff"), mensagem);
}

private void button1_Click(object sender, EventArgs e)
{
    msg("Teste");
}

However, the message "Test" does not appear

    
asked by anonymous 22.09.2017 / 15:41

3 answers

6

Create your own method that receives text as input;)

public void EscreverNoConsole(string texto) {
    Console.WriteLine("[{0}]-{1}", data.ToString("HH:mm:ss:fff"), texto);
}

From there, whenever you want to write to the console, instead of calling Console.WriteLine, call the method you created.

EscreverNoConsole("Quero vê-la sorrir, quero vê-la cantar");
EscreverNoConsole("Quero ver o seu corpo dançar sem parar");

This is called encapsulation. Everything you need to repeat a lot, you can encapsulate in a function or method.

    
22.09.2017 / 15:49
3

You can do this (each line in a very different place, not a sequential code):

using static System.Console;

private static DateTime data = DateTime.Now;

WriteLine($"[{data.ToString("HH:mm:ss:fff")}]");

I would not do it, but if you want to do the same gambiarra:

public static void WL(string format, params args) => WriteLine(format, string[] args);

According to the edit I would do so:

public void CW(string mensagem) => WriteLine($"[{data.ToString("HH:mm:ss:fff")}]-{mensagem}");

Difficult to be "simplifying" more than this.

    
22.09.2017 / 15:48
1

Create a method that receives the message you want to print as a parameter:

public void ExibirMensagem(string msg)
{
    Console.WriteLine("[{0}] - {1}", DateTime.Now.ToString("HH:mm:ss:fff"), msg);
}

So you call the method by passing the text that should be shown and will be displayed in the specified format.

example :

if (1)
    ExibirMensagem("Mensagem número UM");
else if (2)
    ExibirMensagem("Mensagem número DOIS");
else
    ExibirMensagem("Mensagem número TRÊS");

Return :

[10:47:12:756]- Mensagem número UM
[10:47:12:757]- Mensagem número DOIS
[10:47:12:758]- Mensagem número TRÊS
    
22.09.2017 / 15:48