Skip to content

Instantly share code, notes, and snippets.

@benerdin
Created May 30, 2013 14:20
Show Gist options
  • Select an option

  • Save benerdin/5678202 to your computer and use it in GitHub Desktop.

Select an option

Save benerdin/5678202 to your computer and use it in GitHub Desktop.
Code snippet for reflecting on a class and appending properties to a StringBuilder. For System types, this will ignore appending properties (e.g. the Length property won't be appended for System.String).
private string GetModelDescription()
{
var sb = new StringBuilder();
var type = typeof(YourType);
sb.AppendFormat("{0} ({1})\n", type.Name, type.UnderlyingSystemType.ToString());
AppendPropertiesDescription(type, sb, " ");
return sb.ToString();
}
private void AppendPropertiesDescription(Type type, StringBuilder sb, string prefix)
{
type.GetProperties()
.ForEach(prop => {
var underlyingType = prop.PropertyType.UnderlyingSystemType;
// Types we don't need to append
if (!underlyingType.IsGenericType && prop.ReflectedType.Namespace.StartsWith("System"))
return;
// Append type
sb.AppendFormat("{0}{1} ({2})\n", prefix, prop.Name, underlyingType.ToString());
if (underlyingType.IsGenericType)
{
// Type has a generic (e.g. List<object>).
underlyingType.GenericTypeArguments
.ForEach(genType => AppendPropertiesDescription(genType.UnderlyingSystemType, sb, prefix + " "));
}
else
{
// Recursive call to append properties of property.
AppendPropertiesDescription(prop.PropertyType.UnderlyingSystemType, sb, prefix + " ");
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment