1

I have a program that uses Console.WriteLine(); to output to the user in many different locations in the program. Is there a way to get what line the last printed line of output is in the console application? Without incrementing a counter every Console.WriteLine();. For example, in the following code "Bar Foo" would have printed as line 4. Here would be an example program:

Console.WriteLine("Foo");
Console.WriteLine("Foo Bar");
Console.WriteLine("Bar");
Console.WriteLine("Bar Foo");

output:

Foo

Foo Bar

Bar

Bar Foo

mjsting33
  • 13
  • 3
  • Very cood technique posted here: [How to get current line number - for example use at messagebox.show](http://stackoverflow.com/questions/12556767/how-to-get-current-line-number-for-example-use-at-messagebox-show) – Jonathan Wood Oct 07 '14 at 01:49

3 Answers3

1

No you need something custom to keep track of it. However you can internalize it and make your own class that wraps Console.WriteLine to avoid repeated counter logic.

TGH
  • 38,769
  • 12
  • 102
  • 135
1

You can use CallerLineNumber which is introduce in .Net 4.5.
You may have something like this:

static void WriteLine(string message, [CallerLineNumber] int lineNumber = 0)
{
    Console.WriteLine(lineNumber + ": " + message);
}

And in your sourcecode you can simply call it like :

WriteLine("Foo");
WriteLine("Foo Bar");
WriteLine("Bar");
WriteLine("Bar Foo");

If you must use a lower version of .Net you can use :

static void WriteLine(string message)
{
    StackFrame callStack = new StackFrame(1, true);
    var lineNumber = callStack.GetFileLineNumber();
    Console.WriteLine(lineNumber + ": " + message);
}

And again you just need to call it :

WriteLine("Foo");
WriteLine("Foo Bar");
WriteLine("Bar");
WriteLine("Bar Foo");
Hossein
  • 24,202
  • 35
  • 119
  • 224
0

Actually, every time you do a Console.WriteLine(), the cursor moves as well. So you can use the position of the cursor as a 0-based index of the line number:

        Console.WriteLine("Foo" + (Console.CursorTop+1));
        Console.WriteLine("Foo Bar" + (Console.CursorTop + 1));
        Console.WriteLine("Bar" + (Console.CursorTop + 1));
        Console.WriteLine("Bar Foo" + (Console.CursorTop + 1));
Tyress
  • 3,573
  • 2
  • 22
  • 45