Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does LinqPad run ToString() on some types when they are dumped?

Tags:

c#

linqpad

I'm using NuGetVersion from the NuGet.Versioning package in LinqPad. I'm trying to Dump() it to inspect it's properties, but instead of the usual dump I just get the string representation.

For example, this:

var v = new NuGetVersion("1.0.0");
v.Dump();

Shows the following in the output window:

1.0.0

Does anyone know why LinqPad runs ToString() when some types are dumped, and how to change this behaviour?

like image 502
Kevin Kuszyk Avatar asked Jun 16 '16 13:06

Kevin Kuszyk


1 Answers

In general, LINQPad calls ToString() rather than expanding the properties if the object implements System.IFormattable.

You could override this by writing an extension method in My Extensions that uses LINQPad's ICustomMemberProvider:

EDIT: There's now an easier way. Call LINQPad's Util.ToExpando() method:

var v = new NuGetVersion("1.0.0");
Util.ToExpando (v).Dump();

(Util.ToExpando converts the object into an ExpandoObject.)

For reference, here's the old solution that utilizes ICustomMemberProivder:

static class MyExtensions
{
    public static object ForceExpand<T> (this T value)
        => value == null ? null : new Expanded<T> (value);

    class Expanded<T> : ICustomMemberProvider
    {
        object _instance;
        PropertyInfo[] _props;

        public Expanded (object instance)
        {
            _instance = instance;
            _props = _instance.GetType().GetProperties();
        }

        public IEnumerable<string> GetNames() => _props.Select (p => p.Name);
        public IEnumerable<Type> GetTypes () => _props.Select (p => p.PropertyType);
        public IEnumerable<object> GetValues () => _props.Select (p => p.GetValue (_instance));
    }
}

Call it like this:

new NuGetVersion("1.2.3.4").ForceExpand().Dump();
like image 122
Joe Albahari Avatar answered Nov 02 '22 12:11

Joe Albahari