Tuesday, March 6, 2012

How to echo all properties and their values of an object

 static public class Reflect
    {
        public static string GetAllPublicPropertyValues(object o)
        {
            StringBuilder sb = new StringBuilder();
            if (o == null)
            {
                sb.AppendLine("null");
                return sb.ToString();
            }

            try
            {
                sb.AppendFormat("-- {0} --{1}", RemoveNamespace(o.GetType().ToString()), Environment.NewLine);
                PropertyInfo[] properties = o.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
                foreach (PropertyInfo p in properties)
                {
                    MethodInfo mget = p.GetGetMethod(false);
                    if (mget == null) { continue; }     // must have a public get property
                    object val = p.GetValue(o, null);
                    sb.AppendFormat("{0}={1}{2}", RemoveNamespace(p.Name), val != null ? val.ToString() : "null", Environment.NewLine);
                }
            }
            catch (Exception ex)
            {
                sb.AppendLine(ex.ToString());
            }
            return sb.ToString();
        }


        public static string RemoveNamespace(string typeName)
        {
            if (String.IsNullOrEmpty(typeName))
                return string.Empty;

            string[] tok = typeName.Split('.');
            if (tok.Length > 0)
                return tok[tok.Length - 1];

            return string.Empty;
        }
    }