How to Check if a property is an enum with reflection in C#

By FoxLearn 2/4/2025 4:27:13 AM   104
When working with reflection to inspect a class’s properties, you can use PropertyInfo.PropertyType.IsEnum to determine if the property is an enum type.

This is especially useful when you want to safely invoke enum-specific methods (e.g., Enum.GetName()) on a dynamically accessed type, preventing exceptions like ArgumentException: Type provided must be an Enum.

Here’s an example of checking if a property is an enum and then using an enum method:

var prop = typeof(Employee).GetProperty("Position");

if (prop.PropertyType.IsEnum)
{
    foreach (var enumValue in Enum.GetValues(prop.PropertyType))
    {
        Console.WriteLine(enumValue);
    }
}

In this example, since Employee.Position is an enum, the output will display all the possible values of the PositionType enum:

Manager
Developer
Designer
Tester

Check if a property is a specific enum type

If you need to check whether the property is a specific enum type, you can compare the property type directly:

var prop = typeof(Employee).GetProperty("Position");

if (prop.PropertyType == typeof(PositionType))
{
    // do something specific to PositionType enum
}

Set an enum property to a string

You cannot directly assign a string value to an enum property. Attempting to do so results in an exception: ArgumentException: Object of type ‘System.String’ cannot be converted to type 'PositionType'.

Instead, you can use Enum.Parse() or Enum.TryParse() to convert the string into the corresponding enum value.

var newPosition = "Developer"; // Could come from user input, a config, etc...

var employee = new Employee();

var prop = employee.GetType().GetProperty("Position");

if (prop.PropertyType.IsEnum && Enum.IsDefined(prop.PropertyType, newPosition))
{
    prop.SetValue(employee, Enum.Parse(prop.PropertyType, newPosition));
}

Console.WriteLine(employee.Position);

The output will be:

Developer

Set an enum property to a numeric value

You can set an enum property with a numeric value directly via reflection. The value doesn’t have to match a defined enum value, although it’s good practice to check using Enum.IsDefined() to prevent invalid values.

var newPosition = 1; // Could come from user input, a config, etc...

var employee = new Employee();

var prop = employee.GetType().GetProperty("Position");

if (prop.PropertyType.IsEnum && Enum.IsDefined(prop.PropertyType, newPosition))
{
    prop.SetValue(employee, newPosition);
}

Console.WriteLine(employee.Position);

This sets employee.Position to the value 1, which corresponds to PositionType.Developer. The output is:

Developer

When working with reflection and enum properties, it's always a good practice to use PropertyType.IsEnum to confirm that you're dealing with an enum. Additionally, using Enum.IsDefined() ensures you avoid parsing invalid enum values, which can lead to exceptions (or use TryParse() for safer handling).