Home

Cannot override Uri output as string in ToDump()?

ToDump() should allow us to change how an object is dumped. However I noticed that Uri's are still being rendered like a normal Uri object, even if I try to output it as a string. It seems like it is rendered as an object if the string returned matches the AbsoluteUri (the ToString() representation).

void Main()
{
    Enumerable.Range(0, 20).Select(i =>
        (i, new Uri($"http://example.com/{i}.html"))
    ).Dump();
}


static int i = 0;
static object? ToDump(object? obj)
{
    switch (obj)
    {
        case Uri uri:
            return (i++ % 6) switch
            {
                0 => uri.ToString(), // still rendered as an object, not a string
                1 => $"{uri}!", // I just want to output the url without extra text
                2 => $"{uri} ", // apparently space gets trimmed off and is still rendered as an object
                3 => $"{uri}\x200b", // zero-width space at the end works since it's different
                4 => uri, // rendered like a normal object
                _ => "http://google.com", // something completely unrelated renders as string
            };
        default:
            return obj;
    }
}

Comments

  • That's interesting behavior. It occurs because of a bug in the way Equals has been implemented in the Uri class. The following expression returns true:

    new Uri ("http://test").Equals ("http://test")   // true
    

    This is clearly a bug because it's not commutative:

    "http://test".Equals (new Uri ("http://test"))   // false
    

    You can work around it by wrapping the string in a css class or style:

    Util.WithCssClass (uri.ToString(), "none");
    
  • Oh wow, I didn't realize it did that. I thought that sorcery was coming from linqpad. The workaround works for me, though I think in my case, it was more helpful for me to have it as a Hyperlinq instead.

Sign In or Register to comment.