How does the immediate window of visual studio print all members of an object?

1.6k Views Asked by At

How can I using the output window write all the members of an object? Trace.WriteLine uses method ToString and doesn't output all the members. Is there API to do it without writing own code?

3

There are 3 best solutions below

0
On

It's probably iterating through the members via reflection.

4
On

The ToString() method on the particular object gets called, and if that method has been overridden to show all members, then fine. However not all objects have their ToString() methods implemented, in which case the method returns the object type info.

Instead of calling ToString() write a custom function that uses reflection to enumerate the object members, and output that.

Edit: This function will return the given object's properties, add methods, events everything else you need. (It's in VB, no C# on this work PC)

Function ListMembers(ByVal target As Object) As String

    Dim targetType As Type = target.GetType 

    Dim props() As Reflection.PropertyInfo = targetType.GetProperties

    Dim sb As New System.Text.StringBuilder

    For Each prop As Reflection.PropertyInfo In props
        sb.AppendLine(String.Format("{0} is a {1}", prop.Name, prop.PropertyType.FullName))
    Next

    Return sb.ToString

End Function
1
On

You can do something like this:

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;

 namespace ConsoleApplication2
 {
     class Program
     {
         static void Main(string[] args)
         {
             var m = new MyClass { AString = "somestring", AnInt = 60 };

             Console.WriteLine(GetObjectInfo(m));

             Console.ReadLine();
         }

         private static string GetObjectInfo(object o)
         {
             var result = new StringBuilder();

             var t = o.GetType();

             result.AppendFormat("Type: {0}\n", t.Name);

             t.GetProperties().ToList().ForEach(pi => result.AppendFormat("{0} = {1}\n", pi.Name, pi.GetValue(o, null).ToString()));

             return result.ToString();
         }
     }

     public class MyClass
     {
         public string AString { get; set; }
         public int AnInt { get; set; }
     }
}