Is it possible to customize only single member output without rewriting complete record's ToString()?

57 Views Asked by At

I have record with many members and I want Console.WriteLine(myRecord); to output its values. However one of its members is an array and it will be printed as MyOtherRecordType.Item[]

Is there a an easy way to customize output of just that single member without rewriting ToString() completeley?

Here is a very simple repro (fiddle if you want):

using System;
                    
public class Program
{
    public static void Main()
    {
        Console.WriteLine(new Test("a", "b", "c"));
    }
}

record Test(params string[] strings);

The output is:

Test { strings = System.String[] }

And I want it to be more like

Test { strings = {"a", "b", "c"} }

or different, the point is to see values. In my case it's actually not a string[], but another record type array.


I wish there was an attribute, like with json converters, to force ToString() to use converter, but I am afraid the answer is not possible and I have to override ToString() completely. Maybe I can somehow combine the autogenerated ToString() with my code?

I am looking at msdn, but there is nothing inspirational.

1

There are 1 best solutions below

0
Fildor On

Not really a solution, more of a work-around would be to serialize to JSON:

using System;
using System.Text.Json;
                    
public class Program
{
    public static void Main()
    {
        Console.WriteLine((new Test("a", "b", "c")).ToJson());
    }
}

public record Test(params string[] strings);

public static class TestEx
{
    public static string ToJson(this Test test) => JsonSerializer.Serialize(test);
}

In Action: https://dotnetfiddle.net/y3LQaB

Output:

{"strings":["a","b","c"]}

Or a little closer to the desired output:

https://dotnetfiddle.net/pzJHhn

public static string ToJson<T>(this T test) => typeof(T) + JsonSerializer.Serialize(test);

=>

Test{"strings":["a","b","c"]}