Mega Code Archive

 
Categories / C# / Reflection
 

Gets a string with all of the properties that are not null

// <copyright file="Utility.cs" company="Microsoft Corporation"> // Copyright (c) 2009 Microsoft Corporation All Rights Reserved // </copyright> // <author>Michael S. Scherotter</author> // <email>mischero@microsoft.com</email> // <date>2008-10-09</date> // <summary>Silverlight utility classes</summary> using System; using System.Linq; using System.Text; public sealed class Utility {     /// <summary>     /// Gets a string with all of the properties that are not null.     /// </summary>     /// <param name="data">the object to query</param>     /// <returns>a string formatted the property names and values</returns>     public static string GetProperties(object data){         var type = data.GetType();         var properties = type.GetProperties().OrderBy(item => item.Name);         StringBuilder builder = new StringBuilder("-- " + type.FullName + " --");         foreach (var property in properties)         {             var value = property.GetValue(data, null);             if (value != null)             {                 builder.AppendLine();                 builder.AppendFormat(System.Globalization.CultureInfo.CurrentCulture, "{0}: {1}", property.Name, value);             }         }         return builder.ToString();     } }