views:

28

answers:

1

Hi All,

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.

Thanks.

+3  A: 

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
Great. I will try this. Is typeof(string) and typeof(String) equivalent? Will the above with with both a string and String?
peter
OK, written some unit tests and it works a treat. It does indeed treat string and String the same. I expected that, but just wanted to make sure.
peter