Fred
Fred

Reputation: 5808

How to Test Property for Data Type Equality

I am trying to determine the type of a property and assign it a value from an SqlDataReader. Below is my code and the three variations I have seen on here but none of which work. (dr is the DataReader, response.FundsParms is a data class, fields in the DataReader have the same names as the data class)

foreach (
    PropertyDescriptor prop in
        TypeDescriptor.GetProperties(response.FundsParms)
            .Cast<PropertyDescriptor>()
            .Where(prop => HasColumn(dr, prop.Name)))
{
    if (prop.GetType() == string)  //Error here is Expression Expected
    {
        prop.SetValue(response.FundsParms, dr[prop.Name].ToString());
    }
    if (prop.GetType() == typeof(decimal))  //Pre compile message - Operator is can be used
    {
        prop.SetValue(response.FundsParms, Convert.ToDecimal(dr[prop.Name]));
    }
    if (prop is int)  //Error: The given expression is never of the given type
    {
        prop.SetValue(response.FundsParms, Convert.ToInt32(dr[prop.Name]));
    }
}

Where am I going wrong?

Upvotes: 0

Views: 464

Answers (2)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

How about using PropertyType property of TypeDescriptor which return object of the Type of the Property:

if ( prop.PropertyType == typeof(int))

Upvotes: 4

Dan J
Dan J

Reputation: 16708

Notice this:

foreach (
        PropertyDescriptor prop in

The variable prop is of type PropertyDescriptor.

if (prop.GetType() == string)

GetType() returns a Type representing the instance on which it's called. What is the type of the variable prop? It's typeof(PropertyDescriptor).

PropertyDescriptor.PropertyType will identify the type of the property that prop is actually describing.

Upvotes: 2

Related Questions