5-to-9
5-to-9

Reputation: 649

Reflection and how to handle enums

I want to use something similar as:

object ob;
            var props = ob.GetType().GetProperties();

            List<Element> list = new List<Element>();
            foreach (var prop in props)
            {
                if (prop.PropertyType == typeof(String))
                    list.Add(makeStringProperty(prop));
                else if (prop.PropertyType == typeof(int))
                    list.Add(makeIntProperty(prop));
                else
                {
                }
            }

which adds something to the given list for every property in a given object. Now I want to add a clause for also adding enum-variables, including getting all its values by Enum.GetValues() f.e.. That would be easy for any one given enum, but I want this to be generic for every possible enum, so for example if ob would have:

enum Weather {
sunny,
rainy,
cloudy
}
Weather weather = sunny;

enum Places {
beach,
mall,
home
}
Places place = beach;

I would be able to get both variables themselves AND all the values of both Enums. Of course I can't directly check typeof(Enum) or anything. Does someone have a clue?

Upvotes: 0

Views: 251

Answers (2)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61950

It's something like

typeof(Weather).GetFields()

or

ob.GetType().GetFields()

if you want to use reflection directly on an enum type. The members of an enum are a kind of static fields.

But you can also use

Enum.GetValues(ob.GetType())

In any case, if there's doubt, you should check if it is an enum or not first:

var typeOfOb = ob.GetType();
if (typeOfOb.IsEnum)
{
  // use Enum.GetValues(typeOfOb) here
}

Note: System.Type is the class used for both a type determined compile-time, like typeof(Weather), and a type determined run-time, like ob.GetType(). So you can use both as an argument to the GetValues(System.Type) static method.

Upvotes: 0

Lee
Lee

Reputation: 144126

else if(prop.PropertyType.IsEnum)
{
    var values = Enum.GetValues(prop.PropertyType);
}

Upvotes: 1

Related Questions