views:

108

answers:

4

I have an object of class F. I want to output the contents of the object using Console.WriteLine for quick and dirty status updates like this:

Console.WriteLine(objectF);

This prints out only the name of the class to the console:

F

I want to overload this somehow so that I can instead print out some useful information about the object and its properties.

I have a workaround already: To overload the ToString method in my class and then call: Console.WriteLine(objectF.ToString());

But I would rather have the simpler syntax. Any ideas?

+4  A: 

Console.WriteLine(objectF)

Should work, if you overloaded ToString. When the framework needs to convert an object to a string representation, it invokes ToString.

driis
+1  A: 

I would continue to use ToString(). That's its purpose for existing. Also, unless you have a format string, you can just write:

Console.WriteLine(objectF)
Ben Hoffstein
A: 

I found the cause of my problem. I had neglected to define my implementation of ToString() as an override. The correct syntax is:

public override string ToString()
{
   ///Do stuff...
   return string;
}

Thanks to the posters below who put me on the right track

Kevin P.
+1  A: 

You should override ToString() though in some situations you may just find the following code useful:

public static class ObjectUtility
{
 public static string ToDebug(this object obj)
 {
  if (obj == null)
   return "<null>";

  var type = obj.GetType();
  var props = type.GetProperties();

  var sb = new StringBuilder(props.Length * 20 + type.Name.Length);
  sb.Append(type.Name);
  sb.Append("\r\n");

  foreach (var property in props)
  {
   if (!property.CanRead)
    continue;
   // AppendFormat defeats the point
   sb.Append(property.Name);
   sb.Append(": ");
   sb.Append(property.GetValue(obj, null));
   sb.Append("\r\n");
  }

  return sb.ToString();
 }
}

Usage is to simply include the namespace containing ObjectUtility and then...

var f = new F();
Console.WriteLine(f.ToDebug());

The reflection usage above isn't very good for high performance code so don't use it in a production scenario where high performance is desired.

cfeduke