Home

Dump line number

Is there a better way to achieve the dumping of the calling line number?

I tried the following in MyExtensions, but the output line number doesn't correspond to the calling line number in the query:

    public static T DumpEx<T>(this T o, [CallerLineNumber] int callingFileLineNumber = 0)
    {
        return o.Dump(callingFileLineNumber.ToString(), null);
    }

    public static T DumpEx<T>(this T o, string description, [CallerLineNumber] int callingFileLineNumber = 0)
    {
        return o.Dump($"{description} {callingFileLineNumber}", null);
    }

Best regards

John

Comments

  • This won't work because My Extensions is compiled separately and referenced as a DLL.

    You could try writing these extension methods in a separate query and then #load it.

  • Ok, that makes sense. Thank you.

    In that case for anyone else who stumbles across this, the following works for LINQPad 6:

    [DumpEx_Extensions.linq]

    void Main()
    {
    }
    
    public static class DumpExExtensions
    {
        public static T DumpEx<T>(this T o, [CallerLineNumber] int callingFileLineNumber = 0)
        {
            return o.Dump(callingFileLineNumber.ToString(), null);
        }
    
        public static T DumpEx<T>(this T o, string description, [CallerLineNumber] int callingFileLineNumber = 0)
        {
            return o.Dump($"{callingFileLineNumber} {description}", null);
        }
    }
    

    [CallerWithLoad.linq]

    #load ".\Shared\DumpEx_Extensions.linq"
    void Main()
    {
        var name = "Harold";
        var full = $"{name} Wilson";
    
        full.DumpEx("Full name");
    }
    

    Looking at this though, I think I'm going to ditch the DumpEx extensions and just go with a function that returns the line number which will be more flexible. So:

    [LineNumber.linq]

    void Main()
    {
    }
    
    public static int Line([CallerLineNumber] int callingFileLineNumber = 0)
    {
        return callingFileLineNumber;
    }
    

    and usage:

    Using string interpolation makes it more flexible I think.

    Anyway, thank you for the #load feature and love the intellisense when setting:

    If there's an easy option to slip a current line number token into Dump for LINQPad 5 that would be great too!

    Best regards

    John

  • Another option, which will work from My Extensions, is this:

    int lineNumber = new StackTrace(true).GetFrame(1).GetFileLineNumber();

    (Unfortunately, it won't work in LINQPad 5.)

  • Oh good solution, thank you. I'll give that a go in 6.

Sign In or Register to comment.