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