Programming

How to Print an Object by Console.WriteLine in C#

I found the following FAQ (Japanese) and it says that using Microsoft.CodeAnalysis.CSharp.Scripting.

C# インタラクティブでは```> var a = 1;> a1> new List { "x", "yz" }List(2) { "x", "
C# でオブジェクトを見やすくデバッグ表示する - teratail[テラテイル]

For my own reference, I’ll document how to use Microsoft.CodeAnalysis.CSharp.Scripting, as introduced in the FAQ above, in a new console project below.

Commands:

dotnet new console --use-program-main
dotnet add package Microsoft.CodeAnalysis.CSharp.Scripting --version 4.12.0
dotnet build
./bin/Debug/net8.0/FormatTest
# FormatTargetObject { Id=1, Name="John Doe" }

Codes:

namespace FormatTest;

using Microsoft.CodeAnalysis.CSharp.Scripting.Hosting;

class FormatTargetObject
{
    public int Id { get; set; } = 1;
    public string Name { get; set; } = "John Doe";
}

class Program
{
    private static readonly CSharpObjectFormatter formatter = CSharpObjectFormatter.Instance;
    static void Main(string[] args)
    {
        Console.WriteLine(formatter.FormatObject(new FormatTargetObject()));
    }
}

zuqqhi2

Share
Published by
zuqqhi2
Tags: c#