C# – Check if a property is an enum with reflection

When you’re using reflection to look at a type’s properties, you can use PropertyInfo.PropertyType.IsEnum to check if the property is an enum. This is helpful when you want to be able to safely call an Enum API method (such as Enum.Parse()) on the reflected type, thus preventing an exception – ArgumentException: Type provided must be … Read more

C# – Enum generic type constraint

In C# 7.3, Microsoft added the ability to specify an Enum as a generic constraint, like this: Whenever you have a generic method, it’s a good idea to use generic type constraints. Without constraints, you would have to implement type checking in the generic method and throw exceptions if an invalid type was used. With … Read more

C# – Fill a dropdown with enum values

When you need to show enum values in a dropdown, it’s a good idea to automatically populate the list, instead of manually setting all of the values. To fill the dropdown with the enum’s values, set the DataSource to Enum.Values(), like this: Then to get the option the user picked, do the following: When I … Read more

C# – How to use enum flags

Enum flags allow you to put multiple values in an enum variable/parameter. This is a nice alternative to having to pass around a ton of bools. You set multiple values by bitwise ORing them together. Here’s an example: In this article, I’ll show how to create and use enum flags. Use [Flags] attribute on enum … Read more

JsonException: The JSON value could not be converted to Enum

When you’re using System.Text.Json to deserialize JSON that contains the string representation of an enum, you get the following exception: System.Text.Json.JsonException: The JSON value could not be converted to <Enum Type> The following JSON would cause this exception. Conference is an enum, and this is using the string representation “NFC” instead of the numeric value … Read more