Mega Code Archive

 
Categories / C# / Data Types
 

Generate ToString for given object

/*  License:  Microsoft Public License (Ms-PL)    http://c4fdevkit.codeplex.com/license  C4F Developer Kit */ using System; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Windows.Media.Imaging; public class MainClass{         /// <summary>         /// Generates ToString functionality for a struct.  This is an expensive way to do it,         /// it exists for the sake of debugging while classes are in flux.         /// Eventually this should just be removed and the classes should         /// do this without reflection.         /// </summary>         /// <typeparam name="T"></typeparam>         /// <param name="object"></param>         /// <returns></returns>         public static string GenerateToString<T>(T @object) where T : struct         {             StringBuilder sbRet = new StringBuilder();             foreach (PropertyInfo property in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))             {                 if (0 != sbRet.Length)                 {                     sbRet.Append(", ");                 }                // Assert.AreEqual(0, property.GetIndexParameters().Length);                 object value = property.GetValue(@object, null);                 string format = null == value ? "{0}: <null>" : "{0}: \"{1}\"";                 sbRet.AppendFormat(format, property.Name, value);             }             return sbRet.ToString();         } }