Using PropertyInfo to find out the property type

C#.NetReflection

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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;
}

Solution 2 - C#

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);
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpeterView Question on Stackoverflow
Solution 1 - C#Igor ZevakaView Answer on Stackoverflow
Solution 2 - C#AV2000View Answer on Stackoverflow