tags:

views:

344

answers:

4

Hi,

Is there a built in function in C# / .net that will take a variable and describe / output it's contents? In PHP there are the print_r and var_dump functions which achieve this (I realise the inherent difference between C# and PHP, just providing a example of output)

As this is for a logging script it needs to be as lightweight and unintrusive as possible - I'm considering writing a function to do this however would prefer to use a built in if available.

Examples of variables would be arrays / lists of custom objects, dumping out of eventargs passed to an event handler etc. I'd like to take this as far as possible whilst avoiding the expense of reflection.

Thanks

+1  A: 

I'm not sure about any built-in dump functionality in C#, but you could simply use Reflection and iterate through a variable's type with MethodInfo, PropertyInfo, FieldInfo etc.

Edit: Yes, I know it's not exactly lightweight.

SirDemon
A: 

I don't know PHP, but I guess overriding/implementing ToString() in your class is the closest match.

E.g. for a class Person, you could implement ToString() similar to this:

public override string ToString()
{
  return string.Format("{0} {1}", this.FirstName, this.LastName);
}

This would output "firstname lastname" for any instance of Person.

M4N
+1  A: 

See my answer to this question for a summary of different ways to get a string representation of an object:
http://stackoverflow.com/questions/697216/string-casts/697248#697248

Since you want this to be both very generic and lightweight your best option here is probably Convert.ToString().

Joel Coehoorn
I figured I'd end up doing something like that - thanks
Macros
A: 

There is no built-in method for this, but here is an example to get the fields and properties using reflection:

public static string DisplayObjectInfo(Object o)
{
   StringBuilder sb = new StringBuilder();

   // Include the type of the object
   System.Type type = o.GetType();
   sb.Append("Type: " + type.Name);

   // Include information for each Field
   sb.Append("\r\n\r\nFields:");
   System.Reflection.FieldInfo[] fi = type.GetFields();
   if (fi.Length > 0)
    {
      foreach (FieldInfo f in fi)
      {
         sb.Append("\r\n " + f.ToString() + " = " +
                   f.GetValue(o));
      }
   }
   else
      sb.Append("\r\n None");

   // Include information for each Property
   sb.Append("\r\n\r\nProperties:");
   System.Reflection.PropertyInfo[] pi = type.GetProperties();
   if (pi.Length > 0)
   {
      foreach (PropertyInfo p in pi)
      {
         sb.Append("\r\n " + p.ToString() + " = " +
                   p.GetValue(o, null));
      }
   }
   else
      sb.Append("\r\n None");

   return sb.ToString();
}

Source: http://www.developer.com/net/csharp/article.php/3713886

John Rasch