15

I need to dump the content of arrays or objects and I am interested to know if in C# we have something like PHP instruction var_dump.

The objective is to not build a loop to use every property or content of array or object and print with Console.WriteLine.

Christoph Fink
  • 22,099
  • 9
  • 67
  • 105
David
  • 6,388
  • 9
  • 30
  • 50

4 Answers4

17

The closest thing would probably be string.Join:

Console.WriteLine(string.Join(", ", myEnumOfObjects));

It would not automatically include "every property or content of array or object" into the output, though - if you want that to happen, you need to override the ToString method of the object being printed:

class MyObject {
    public string Name {get;set;}
    public DateTime Dob {get;set;}
    public override string ToString() {
        return string.Format("{0} - {1}", Name, Dob);
    }
}
Community
  • 1
  • 1
Sergey Kalinichenko
  • 697,062
  • 78
  • 1,055
  • 1,465
3

When you insert a break point you can easily view the contents of an array by hovering your mouse over it.

or any of these:

You are probably using Console.WriteLine for printing the array.

int[] array = new int[] { 1, 2, 3 };
foreach(var item in array)
{
    Console.WriteLine(item.ToString());
}

If you don't want to have every item on a separate line use Console.Write:

int[] array = new int[] { 1, 2, 3 };
foreach(var item in array)
{
    Console.Write(item.ToString());
}

or string.Join (in .NET Framework 4 or later):

int[] array = new int[] { 1, 2, 3 };
Console.WriteLine(string.Join(",", array));

from this question: How to print contents of array horizontally?

Community
  • 1
  • 1
Stijn Bernards
  • 1,103
  • 11
  • 29
3

I think there aren't direct equivalent of var_dump php function.

You must use reflection to write an equivalent function.

If you search in web, you can easily find code which do it.

For example : http://ruuddottech.blogspot.fr/2009/07/php-vardump-method-for-c.html

binard
  • 1,665
  • 1
  • 17
  • 26
1

I know you want to avoid loop, but if its just for the sake of writing multiple lines of code, below is a one liner loop that could allow you to print data with single line for Objects extend ForEach Method

List<string> strings=new List<string>{"a","b","c"};//declare one

strings.ForEach(x => Console.WriteLine(x));//single line loop...for printing and is easier to write
Ronak Agrawal
  • 976
  • 1
  • 17
  • 47
  • var_dump can print any value of one object ... classes, integers, any .... simply with vardump(object_variable), the idea is not to make a loop – David Mar 27 '19 at 08:08