Skip navigation

In my NHibernate core classes I decided to have more informative ToString method, and so I’ve done something like that:

public override string ToString()
{
  StringBuilder sb = new StringBuilder();
  var props = TypeDescriptor.GetProperties(this);
  foreach (PropertyDescriptor p in props)
  {
      sb.AppendFormat("{0} : {1} \n", p.Name, p.GetValue(this));
  }
  return sb.ToString();
}

Very simple, isn’t it? … But it is wrong!

The code above results in Stackoverflow exception. You will not find any information on that in search engine as certain very popular site has such name ;-) and so all find results points there..

Ok so my new ToString():

public override string ToString()
{
  StringBuilder sb = new StringBuilder();
  sb.Append(base.ToString());

  var props = GetType().GetProperties()
      .Where(p => Attribute.IsDefined(p, typeof(DomainSignatureAttribute), true) &&
      (!p.PropertyType.IsSubclassOf(typeof(IEnumerable))) &&
      (!p.PropertyType.IsSubclassOf(typeof(BaseObject))));

  if (props.Count() > 0)
  {
      sb.AppendLine();
  }

  foreach (PropertyInfo p in props)
  {
        sb.AppendFormat("{0} : {1} \n", p.Name, p.GetValue(this, null));
  }
  return sb.ToString();
}

As I use a concept of DomainSignatureAttribue (from Sharp Architecture) and so I decided to show only those properties in ToString() method. I filter collections and other entities that my class refer out, as well, so there should be no circular code references any more.

And I’ve get rid of stack overflow :-) .

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.