Print the contents of an array (code is one line, for use in Immediate window of visual studio)

Viewed 37190

Can you write a convenient line of code that prints the contents of an array?

I will use this in the Immediate Window of Visual Studio 2008, so really it has to work in that window. I may have left out some requirements, but that's pretty much what I'm trying to do.

10 Answers
myArray.ToList().ForEach(Console.WriteLine);

Honestly though, I don't think that'll work in the immediate window. It is a nice trick to print it all in one line, but I think for the immediate window, all you need is this:

? myArray

For both the Watch and Immediate windows in Visual Studio, the string returned by ToString() for an object will be used.

So you can override ToString() if you want and format the human-readable representation of any of your classes so that they display the information you need in the Watch or Immediate windows during debugging activities.

For example,

public class Foo
{
   public String Bar { get; set; }
   private Int32 _intValue;
   public Int32 Value { get { return _intValue; } }
   override public ToString()
   {
      return "Bar: " + Bar + " has Value: " + Value;
   }
}

So now if you create an array of Foo objects named fooArray, typing ? fooArray in the Immediate window will list all the Foo objects with the ToString() return value for each in curly braces. Something like this:

? fooArray
{Foo[2]}
[0]: {Bar: hi has Value: 1}
[1]: {Bar: there has Value: 2}

Might be easier to just use the watch tab. But simply typing the name of the array in the immediate tab should return the contents in a somewhat useful format.

If you want print for example a array m of type float[4][4] just type:(float(*)[4][4])m

Related