130

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.

2 Answers 2

259

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;
}
2
  • The IsAssignableFrom method: msdn.microsoft.com/en-us/library/… will work in more cases (instead of the equal operator, e.g. generics)
    – martin
    May 31, 2016 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 9, 2020 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);
    }
1
  • 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, 2020 at 1:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.