Emile v Rooyen
Emile v Rooyen

Reputation: 49

See Data Type of Object

I am looping through a list of objects. Each object can contain one or more properties. I want to see if the property is either: a string, a numerical value, a boolean, or a Date time.

I did some research and found out to get the property type you can use:

object prop in item.GetType().GetProperties();

So I updated my looping to:

        foreach (var item in myGenericList)
        {
            foreach (object prop in item.GetType().GetProperties())
            {
                //Combobox
                if (prop.Equals(typeof(string)))
                {
                    GenerateComboBox(prop);
                }
                else if (prop is decimal || prop is int || prop is double)
                {
                    GenerateRangeControl(prop);
                }
                else if (prop is bool)
                {
                    GenerateToggle(prop);
                }
                else if (prop is DateTime)
                {
                    GenerateDatePicker(prop);
                }
            }
        }

But none of the conditions are being met. (No if-condition is true) How can I loop through a generic list of objects and find the data type of each property inside the object?

Upvotes: 0

Views: 103

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500055

GetProperties returns the properties themselves, as references PropertyInfo objects. A PropertyInfo isn't a string, or a decimal etc - it's the property, not the value of the property.

If you want to get the value of each property, you want something like:

foreach (var property in item.GetType().GetProperties())
{
    var propertyValue = property.GetValue(item);
    // Now use propertyValue
}

If you need to ignore setter-only properties (which are really rare) you can do that easily enough via filtering:

foreach (var property in item.GetType().GetProperties().Where(pi => pi.CanRead))
{
    var propertyValue = property.GetValue(item);
    // Now use propertyValue
}

If you don't need the value, just the type, you can use the PropertyType property to determine the type of the property.

Upvotes: 3

astef
astef

Reputation: 9478

You need to check PropertyType:

if (prop.PropertyType == typeof(string))
{
    GenerateComboBox(prop);
}
else if (prop.PropertyType == typeof(decimal)
    || prop.PropertyType == typeof(int)
    || prop.PropertyType == typeof(double))
{
    GenerateRangeControl(prop);
}
// ... and so on

Upvotes: 0

Related Questions