Console.WriteLine() Tracing made easy
Consider you are having a complicated object and you want to write some attributes of it to your test-only command line program. For this article it might just be a person:
1 | var person = new Person |
What would you normally do to write all these attributes to the console?
WriteLine()?
1 | Console.WriteLine("Name: "+person.Name); |
Or would you overwrite ToString()?
1 | public override string ToString() |
Works okay too, but you cannot use ToString() for other purposes anymore.
So I thought, I am giving JSON a try for this purpose:
Open your package manager console and write:
install-package Newtonsoft.Json
And then do just this:
1 | Console.WriteLine("MyPerson: " + JsonConvert.SerializeObject(person)); |
The good thing is, it works with basically any object, always prints all members and you do not have to change your ToString() method. Of course there are downsides. You may not want to see all members or if you look closely, in its default settings it is interpreting the enum as an int, but its good enough for me.