Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PropertyInfo to find out the property type

People also ask

How do you check if property is of type is a class?

Examples. The following example creates an instance of a type and indicates whether the type is a class. type MyDemoClass = class end try let myType = typeof<MyDemoClass> // Get and display the 'IsClass' property of the 'MyDemoClass' instance. printfn $"\nIs the specified type a class? {myType.

What is PropertyInfo?

< Previous Next > The PropertyInfo class discovers the attributes of a property and provides access to property metadata. The PropertyInfo class is very similar to the FieldInfo class and also contains the ability to set the value of the property on an instance.

What is property C#?

Properties overview Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code. A get property accessor is used to return the property value, and a set property accessor is used to assign a new value.


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

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