views:

412

answers:

2

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.

A: 
static void DoWork()
{
    var myclass = typeof(MyClass);
    var pi = myclass.GetProperty("Enum");
    var type = pi.PropertyType;

    /* as itowlson points out you could just do ...
        var isMyEnum = type == typeof(MyEnum) 
        ... becasue Enums can not be inherited
    */
    var isMyEnum = type.IsAssignableFrom(typeof(MyEnum)); // true
}
public enum MyEnum { A, B, C, D }
public class MyClass
{
    public MyEnum Enum { get; set; }
}
Matthew Whited
It might be clearer just to test type == typeof(MyEnum). IsAssignableTo doesn't add any value because you can't have another type deriving from MyEnum.
itowlson
Thank you @Matthew. Works like a bought one.
griegs
+1  A: 

In your above code,

bool isEnum = typeof(Enum).IsAssignableFrom(typeof(genericType));

will get you whether or not the current type is (derived from) an enum or not.

adrianbanks
+1 Thanks @adrianbanks for your contribution.
griegs