How to print any arbitrary variable in C# so as to print all members?
I found three answers with the same technique:
- https://stackoverflow.com/a/26181763/2125837 which suggests serializing with Json.NET among other answers, and
- https://tech.io/playgrounds/2098/how-to-dump-objects-in-c/using-json-and-yaml-serializers,
- https://www.codeproject.com/Articles/1194980/How-to-Dump-Object-for-Debugging-Purposes-in-Cshar
However, when I tried it out, with the following code,
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public static class Program
{
public static void Main()
{
Test t1 = new Test(1, 2);
{
string json = JsonConvert.SerializeObject(t1, Formatting.Indented);
Console.WriteLine(json);
}
Dump(t1);
// Add 3 objects to a List.
List<Test> list = new List<Test>();
list.Add(new Test(1, 2));
list.Add(new Test(3, 4));
list.Add(new Test(5, 6));
Console.WriteLine(list.ToString());
{
string json = JsonConvert.SerializeObject(list, Formatting.Indented);
Console.WriteLine(json);
}
}
public class Test
{
int A;
int b;
public Test(int _a, int _b)
{
A = _a;
b = _b;
}
};
public static void Dump<T>(this T x)
{
string json = JsonConvert.SerializeObject(x, Formatting.Indented);
Console.WriteLine(json);
}
}
All that I got are empty Test
outputs:
{}
{}
System.Collections.Generic.List`1[Program+Test]
[
{},
{},
{}
]
Why are all my class members missing when serializing to JSON with Json.NET?