Home > front end >  How to write variable contents to Console?
How to write variable contents to Console?

Time:06-28

I want to use var_dump to show the data held in a variable in C#, but I don't know the function to that in C#. If I use Console.Write(), I can only do it with a specific variable.

For example I want to vardump everything from data:

class Data {
  int total_data = 21,
  int total_page = 1,
  int page = 1,
  int limit = 21
}

var data = new Data();
Console.WriteLine(data.total_data);

How can I get something similar to PHP's var_dump in C#? I've tried using Console.WriteLine(data) but it doesn't work the same way. How can I do this?

CodePudding user response:

if it is from json to handle or create api,you could try serialize it to JSON string with JsonConvert.SerializeObject(data)

CodePudding user response:

You can:

  • override the ToString method
  • use a record type insted of a class (the complier synthesizes ToString for you)
  • create a static helper method that takes an object and uses reflection to print values of all properties
  • have ToConsole() method on the class
  • serialise the object to json and print that

CodePudding user response:

There is a library I'm using for this, ObjectDumper.NET
Sample from the README:

static void Main(string[] args)
{
    var persons = new List<Person>
    {
        new Person { Name = "John", Age = 20, },
        new Person { Name = "Thomas", Age = 30, },
    };

    var personsDump = ObjectDumper.Dump(persons);

    Console.WriteLine(personsDump);
    Console.ReadLine();


//CONSOLE OUTPUT:
{ObjectDumperSample.Netfx.Person}
  Name: "John"
  Age: 20
{ObjectDumperSample.Netfx.Person}
  Name: "Thomas"
  Age: 30
  •  Tags:  
  • c#
  • Related