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


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.



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  


I use:

BitConverter.ToString(bytes); //output: 4A-0B-11-13  etc.  

Poor BitConverter, always forgotten.


where a is the array



String.Join("; ", 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}  


Remember that you can reference a method in the program you are debugging. I have a utility method (let's say it's in a MyDebug class):

    public static string ToReadableString(byte[] data)      {          int length = data.Length;          var sb = new StringBuilder(length);          for (int index = 0; index < length; ++index)          {              char ch = (char)data[index];              sb.Append(Char.IsControl(ch) ? '.' : ch);          }          return sb.ToString();      }  

and (since my array is named data) add a Watch statement:



You can always create a second variable with the content that you want and check for the value of that.

var ids = people.Select(s => s.id).ToList();  

Would return all of the ids that you are trying to see.


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:



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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »