views:

91

answers:

5

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.

+1  A: 
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
BFree
Can't use lambdas, and can't assume that Linq is being referenced.
mletterle
Good point, I remove the lambda.
BFree
"Error Binding to Target method"
MedicineMan
what about if the array is a class called person, and you want to print the address of each person
MedicineMan
If you really only want the immediate window, then override ToString() in your Person class.
BFree
A: 

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.

mletterle
+1  A: 

where a is the array

?a
Paul Creasey
Don't even need the question mark
mletterle
+1  A: 

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}
Canoehead
many times you will not own the class that you are using / debugging
MedicineMan
Not precisely true. The string returned by `ToString()` will not be used (at least in the case of Watch but maybe in Immediate) if you have a `DebuggerDisplay` attribute.
Brian
Thanks Brian for tip about DebuggerDisplay.
Canoehead
A: 

I had this problem with the byte array contained within a MemoryStream - I found this worked to view the contents of the MemoryStream in the Visual Studio 2010 Watch window:

System.Text.ASCIIEncoding.ASCII.GetString(((((System.IO.MemoryStream)(s)))._buffer))
Mike Kelly