138

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 will be doing 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;
}

Really the only part I care about at the moment is 'if the property is a string'. How can I find out from a PropertyInfo object what type it is?

I will have to deal with basic stuff like strings, ints, doubles. But I will have to also deal with objects too, and if so I will need to traverse the object tree further down inside those objects to validate the basic data inside them, they will also have strings etc.

Pang
  • 9,564
  • 146
  • 81
  • 122
peter
  • 13,009
  • 22
  • 82
  • 142

2 Answers2

267

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;
}
Igor Zevaka
  • 74,528
  • 26
  • 112
  • 128
  • The IsAssignableFrom method: https://msdn.microsoft.com/en-us/library/system.type.isassignablefrom(v=vs.110).aspx will work in more cases (instead of the equal operator, e.g. generics) – martin May 31 '16 at 19:28
  • 2
    How to find the type of a property which is not a String nor int but a custom class? e.g. public classA objA; – Hisham Mar 09 '20 at 16:24
3

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);
    }
AV2000
  • 459
  • 5
  • 5
  • 4
    I agree that this could be a useful little function, but I don't believe that the loop has been skipped at all. The LINQ 'Where' is where the loop is taking place. – Peter Dec 27 '20 at 01:48