Home

How to customize Dump for basic types?

It seems that static ToDump customization is only called for complex types. It is not invoked for basic types like strings, int, etc. Is there a way to customize string output?

Here's my reason for wanting to do this. Part of my code is emitting strings with ascii color codes. Linqpad doesn't properly visualize them (btw would you consider adding that as a feature?). But as a workaround I wanted to customize Dump for strings to rewrite ascii color codes as html coloring tags. But it doesn't seem to be possible to override that atm.

Comments

  • edited November 10

    Run as C# Program. See also LINQPad help (Ctrl+F1) for ToDump and related samples.

    // It should be Program for static object ToDump below;
    // you can also move static class Extensions to
    // another file and #load it.
    void Main()
    {
        // Wrap to AsAsciiString. Required for static object ToDump below.
        "red bold value".AsAsciiString().Dump();
    }
    
    static object ToDump(object obj) =>
        obj switch
        {
            // Render as HTML. Maybe there is a 
            AsciiString s => Util.RawHtml($@"<span style=""color: red; font-weight: bold"">{System.Net.WebUtility.HtmlEncode(s)}</span>"),
            _ => obj
        };
    
    public record AsciiString(string Str)
    {
        public static implicit operator string(AsciiString s) =>
            s.Str;
    
        public override string ToString() =>
            Str;
    }
    
    static class Extensions
    {
        public static AsciiString AsAsciiString(this string s) =>
            new AsciiString(s);
    }
    
  • You can also implement ToDump as a class method, look for Customizing Dump in LINQPad samples.

Sign In or Register to comment.