views:

101

answers:

3

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?

+1  A: 

It's probably iterating through the members via reflection.

Yann Schwartz
A: 

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
Wez
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.
alga
There's no magic method here. VS is just calling or evaluating the members via reflection.
Yann Schwartz
What Yann said; VS uses the framework's reflection, and you can do the same. See the code-edit.
Wez
Sorry I didn't scroll up and saw the code added above the ad. oops. Good call Klausbyskov ;)
Wez
+1  A: 

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; }
     }
}
klausbyskov
Thanks. If I don't find the API, I will probably use your code.
alga