.NET's equivalent to Python's repr() or Ruby's Object#inspect?


#1

Hi, I had been mostly a Python programmer, but now I’ve started to learn and use C# for production at my new work. Although everything in C# and .NET is refreshing and exciting to me, but I feel inconvenience sometimes.

One of these things is lack of debug-friendly string formatter, like Python’s repr() or Ruby’s Object#inspect.

For folks who are not aware of it, Python and Ruby also have a equivalent method to .NET’s Object.ToString(): str() and Object#to_s. Python’s repr() and Ruby’s Object#inspect are similar to str() and Object#to_s. Both return a human-readable string. But the intended audience is different. Whereas str() and Object#to_s are for end users, in other say, people who use the program written in Python and Ruby and likely unable to code in these languages, repr() and Object#inspect are for programmers who write and maintain the program. As purposes differ, their contents also differ.

For example, whereas str("hello\n") returns "hello\n", repr("hello\n") returns "\"hello\\n\"". If the former is written in the standard output or a file, it looks like:

hello

but the latter is like:

"hello\n"

The thing is, it is easy to copy and paste into the code editor. It also prevent optical illusion when we need to see strings that contain some control characters.

Another reason why it is useful is because it is quite good at showing nested structures. For example, when we have a list of sets of strings like a = [{"hello", "world"}, {"bye"}], repr(a) returns "[{\"hello\", \"world\"}, {\"bye\"}]", not a string never showing the contents like "list".

I am using Object.ToString() instead for that purpose now, but I feel it’s not enough everyday. I guess it is due to cultural differences. Programmers who write code in Python or Ruby tend to use a light text editor instead of IDE, and live in Unix terminal long time. There’s no graphical visualization of runtime objects, and they prefer logs over debuggers. Although I also fall in love with Rider’s graphical debugger, when I need to do troubleshooting without debugger, like reproducing the problem my customer reported in my laptop, I still miss things like repr()/Object#inspect. At this time, I have to write long lines of formatting code for text logging.

So I wish .NET also has an equivalent to Python’s repr() or Ruby’s Object#inspect. Is it only me?


#2

There is indeed nothing built-in in .Net for that specific purpose. I can see two options:

  1. Find or create a library that does this. After a short search, I found ObjectPrinter, which might suit your needs.
  2. Use a JSON serializer. JSON strings are fairly readable and JSON serializers (like JSON.NET) are well supported, so this could be a reasonable solution.

.NET Foundation Website | Blog | Projects | Code of Conduct