Using PropertyInfo to determine the type of property

I want to dynamically parse a tree of objects in order to perform some random check. Validation is not important as such, but I want to better understand the PropertyInfo class.

I will do something like this,

public bool ValidateData(object data) { foreach (PropertyInfo propertyInfo in data.GetType().GetProperties()) { if (the property is a string) { string value = propertyInfo.GetValue(data, null); if value is not OK { return false; } } } return true; } 

In fact, the only part I care about right now is "if the property is a string." How can I find out from the PropertyInfo object what type it is.

I will have to deal with basic things like strings, ints, double. But I will also have to deal with objects, and if so, I will need to traverse the tree of objects further inside these objects in order to check the main data inside them, they will also have rows, etc.

Thank.

+72
reflection c #
Sep 16 '10 at 5:26
source share
1 answer

Use PropertyInfo.PropertyType to get the property type.

 public bool ValidateData(object data) { foreach (PropertyInfo propertyInfo in data.GetType().GetProperties()) { if (propertyInfo.PropertyType == typeof(string)) { string value = propertyInfo.GetValue(data, null); if value is not OK { return false; } } } return true; } 
+136
Sep 16 '10 at 5:28
source share



All Articles