Skip to content

Instantly share code, notes, and snippets.

@hanssens
Last active August 29, 2015 14:08
Show Gist options
  • Save hanssens/9a2c162d425330cdbfe5 to your computer and use it in GitHub Desktop.
Save hanssens/9a2c162d425330cdbfe5 to your computer and use it in GitHub Desktop.
List all property names and values with reflection
/// <summary>
/// Iterates through each and every property for the specified object and lists its value, including nulls.
/// </summary>
static void ListAllPropertyNamesAndValues(object obj)
{
var t = obj.GetType();
var properties = t.GetProperties();
foreach (var prop in properties)
{
Console.WriteLine("Name: " + prop.Name + ", Value: " + prop.GetValue(obj, null));
}
}
/// <summary>
/// Iterates through each and every property for the specified object and only lists its value if it is not null.
/// </summary>
static void ListOnlyPropertiesWithValues(object obj)
{
var t = obj.GetType();
var properties = t.GetProperties();
foreach (var prop in properties)
{
var value = prop.GetValue(obj, null);
if (value != null)
Console.WriteLine("Name: " + prop.Name + ", Value: " + prop.GetValue(obj, null));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment