Listing properties of an object

  • Thread starter Thread starter John
  • Start date Start date
J

John

Hi

Is there an easy or a built-in way to collect all properties of an object
into a string variable for debugging purpose? I am looking for something
similar to this;

"Property1: Property1value
Property2: Property2value
Property3: Property3value
.....
Propertyn: Propertynvalue"

Thanks

Regards
 
Hi,
Is there an easy or a built-in way to collect all properties of an object
into a string variable for debugging purpose?

I don't think there is. If you're very up to date and using LINQ already,
you could use the ObjectDumper that comes with it as a tool. Otherwise,
this article may be helpful to you:

http://www.codeproject.com/csharp/debugwriter.asp


Oliver Sturm
 
John said:
Is there an easy or a built-in way to collect all properties of an object
into a string variable for debugging purpose?

My preference is to create a ToString() method for each class that tells
me "enough" about the object that I can see what's going on (or, at the
very least, to identify which /instance/ of the object I'm looking at!).

Public Overrides Function ToString()
Return Me.X & ", " & Me.Y
End Function

Of course, there's nothing to stop you adding a "debugging" overload as
well ...

Public Overrides Overloads Function ToString(ByVal debug as Boolean)
If debug Then
Dim sDebugData as String _
= ... lots of stuff ...
Else
Return Me.ToString()
End If
End Function

HTH,
Phill W.
 
Simplest way I believe is:

Type t = f.GetType();

PropertyInfo[] props = t.GetProperties();

foreach (PropertyInfo pi in props) {

Console.WriteLine("Property {0}, value {1}", pi.Name, pi.GetValue(f, null));

}


Here is sample of produced output for a form (f = new Form();)

....

Property BackgroundImage, value
Property BackgroundImageLayout, value Tile
Property Bottom, value 322
Property Bounds, value {X=22,Y=22,Width=300,Height=300}
Property CanFocus, value False
Property CanSelect, value False
Property Capture, value False
Property CausesValidation, value True
Property ClientRectangle, value {X=0,Y=0,Width=292,Height=273}
Property CompanyName, value Microsoft Corporation
Property ContainsFocus, value False
Property ContextMenu, value
Property ContextMenuStrip, value
Property Controls, value System.Windows.Forms.Form+ControlCollection
Property Created, value False
Property Cursor, value [Cursor: Default]
Property DataBindings, value System.Windows.Forms.ControlBindingsCollection

....

You'll might need to tweak BindingFlags and indexes to get to arrays and
special cases, however this should do the desired in most cases

Have fun
Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top