How to simulate the printing of object like in C# Interactive Console?

Viewed 149

An example:

enter image description here

If we type scoreDir in the C# Console, its content is pretty printed, i.e. the definition of the object, its length and its data.

I would like to simulate this printing with a built-in .NET method, e.g. ToString(). However, ToString() doesn't work, as showed. "Simulate" means I can generate the same printed string, but store it in a variable. Microsoft must have used some function to print such object; it's best to just re-use the function (no re-inventing the wheels).

2 Answers

Credits to @Hans Passant in the comment section.

In Visual Studio, after installing the Nuget package Microsoft.CodeAnalysis.CSharp.Scripting, the static function Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.CSharpObjectFormatter.Instance.FormatObject() can be used to mimic the same output as C# Interactive Console.

Here is the code that works:

using System;
using System.IO;
using System.Collections.Concurrent;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var scoreDir = new ConcurrentDictionary<(int, int), (double, int)>();
            scoreDir.TryAdd((1, 2), (0.9, 3));
            var res = Microsoft.CodeAnalysis.CSharp.Scripting.Hosting.CSharpObjectFormatter.Instance.FormatObject(scoreDir);
            Console.WriteLine(res);
        }
    }
}

Result:

enter image description here

There is no such build tool for this but you can convert it to Json. The problem with your example that is not so easy for a ConcurrentDictionary.

IMPORTANT NOTE:
This only will work for Newtonsoft and .NET 6.0 since System.Text.Json does not provide a cast for serialize to JSON ConcurrentDictionary and this also don't work for Newtonsoft in .NET Framework

How to Serialize to JSON string a ConcurrentDictionary?

Import Newtonsoft.Json from Nugget

Add using Newtonsoft.Json; to the references in the head of the file

ConcurrentDictionary<(int,int), (double,int)> scoreDir = new ConcurrentDictionary<(int,int), (double,int)>();
scoreDir.TryAdd((1,2),(0.9,3));
string jsonString = JsonConvert.SerializeObject(scoreDir);
Console.WriteLine(jsonString);

Returns:

{"(1, 2)":{"Item1":0.9,"Item2":3}}

Fiddle: https://dotnetfiddle.net/XzHHoN

Related