Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if a PropertyInfo is of a particular enum type?

I have the following code:

public class DataReader<T> where T : class
{
    public T getEntityFromReader(IDataReader reader, IDictionary<string, string> FieldMappings)
    {
        T entity = Activator.CreateInstance<T>();
        Type entityType = entity.GetType();
        PropertyInfo[] pi = entityType.GetProperties();
        string FieldName;

        while (reader.Read())
        {
            for (int t = 0; t < reader.FieldCount; t++)
            {
                foreach (PropertyInfo property in pi)
                {
                    FieldMappings.TryGetValue(property.Name, out FieldName);

                    Type genericType = property.PropertyType;

                    if (!String.IsNullOrEmpty(FieldName))
                        property.SetValue(entity, reader[FieldName], null);
                }
            }
        }

        return entity;
    }
}

When I get to a field of type Enum, or in this case NameSpace.MyEnum, I want to do something special. I can't simply SetValue because the value coming from the database is let's say "m" and the value in the Enum is "Mr". So I need to call another method. I know! Legacy systems right?

So how do I determine when a PropertyInfo item is of a particular enumeration type?

So in the above code I'd like to first check whether the PropertyInfo type is of a specif enum and if it is then call my method and if not then simply allow SetValue to run.

like image 749
griegs Avatar asked Oct 08 '09 23:10

griegs


1 Answers

Here is what I use with success

property.PropertyType.IsEnum
like image 186
Valamas Avatar answered Oct 16 '22 14:10

Valamas