Monday, July 09, 2007

override ToString() with reflection

because i wanted to have a simple way to print my objects I adapted the following way to create my ToString() method within my objects:

(please not, do not use reflection within high performance environment)

#region Override Methods
/// <summary>
/// Returns a <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
/// </returns>

public override string ToString()
{
StringBuilder sb = new StringBuilder();
#region Start Logging
Log.Debug("Entering method: " + ((object)MethodBase.GetCurrentMethod()).ToString());
sb.Append("Entering method: " + ((object)MethodBase.GetCurrentMethod()).ToString() + Environment.NewLine);
#endregion Start Logging

#region Override ToString() default with reflection

Type t = this.GetType();
PropertyInfo[] pis = t.GetProperties();
for (int i = 0; i < pis.Length; i++)
{
try
{
PropertyInfo pi = (PropertyInfo)pis.GetValue(i);
Log.Debug(
string.Format(
"{0}: {1}",
pi.Name,
pi.GetValue(this, new object[] { })
)
);
sb.AppendFormat("{0}: {1}" + Environment.NewLine, pi.Name, pi.GetValue(this, new object[] { }));
}
catch (Exception ex)
{
BEShared.Utility.Log.Error("Could not log property. Ex. Message: " + ex.Message);
}
}
#endregion Override ToString() default with reflection

return sb.ToString();
}

#endregion Override Methods

No comments:

Shared Cache - .Net Caching made easy

All information about Shared Cache is available here: http://www.sharedcache.com/. Its free and easy to use, we provide all sources at codeplex.

Facebook Badge