I want to dynamically parse an object tree to do some custom validation. The validation is not important as such, but I want to understand the PropertyInfo class better.
I just stumbled upon this great post. If you are just checking whether the data is of string type then maybe we can skip the loop and use this struct (in my humble opinion)
public static bool IsStringType(object data)
{
return (data.GetType().GetProperties().Where(x => x.PropertyType == typeof(string)).FirstOrDefault() != null);
}
Use PropertyInfo.PropertyType to get the type of the property.
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;
}