1

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?

Oleksandr G
  • 2,060
  • 3
  • 22
  • 31

3 Answers3

4

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; }
     }
}    
Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
2

It's probably iterating through the members via reflection.

Yann Schwartz
  • 5,954
  • 24
  • 27
0

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
invert
  • 2,016
  • 14
  • 20
  • No,no. The class, what I'm trying to output doesn't have overridden ToString and I don't want to write it. But the immediate window somehow prints everything. I'm looking for that magic method. – Oleksandr G Dec 04 '09 at 09:48
  • There's no magic method here. VS is just calling or evaluating the members via reflection. – Yann Schwartz Dec 04 '09 at 10:23
  • What Yann said; VS uses the framework's reflection, and you can do the same. See the code-edit. – invert Dec 04 '09 at 14:57
  • Sorry I didn't scroll up and saw the code added above the ad. oops. Good call Klausbyskov ;) – invert Dec 04 '09 at 14:58