Last active
August 29, 2015 14:08
-
-
Save hanssens/9a2c162d425330cdbfe5 to your computer and use it in GitHub Desktop.
List all property names and values with reflection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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