How to make multilingual enum while displaying on the screen.

How to make multilingual enum while displaying on the screen.


While discussing our topic, we will consider it as multiple languages. If you are not going to use multiple languages, you can ignore the localization parts.

Let's have a sample enum like this

public enum EnumEntityStatus
{
    ACTIVE = 0,
    PASSIVE = 1,
    DELETED = 2
}
  • First, let's create our localization file. (Add the LResources.resx file as a new item.)
  • Open this file in your IDE and change the Access Modifier to Public.
  • Fill in Names and Values respectively.
  1. ACTIVE, Actived Record
  2. PASSIVE, Passive Record
  3. DELETED, Deleted Record

Our localization file is ready. Let's set the Enum now. If you are not going to make multilanguage, you can delete the ResourceType parameter.

public enum EnumEntityStatus
{
   [Display(Description = "ACTIVE", ResourceType = typeof(LResources))]
    ACTIVE = 0,
   [Display(Description = "PASSIVE", ResourceType = typeof(LResources))]
    PASSIVE = 1,
   [Display(Description = "DELETED", ResourceType = typeof(LResources))]
    DELETED = 2
}

Yes, everything is fine so far, so how do we show these values on the screen? We will use Reflection for this. We will also write extensions for Enums and our code will be more generic.

public static string GetDisplayDescription(this Enum enumValue)
    {
        if (enumValue != null)
            return enumValue.GetType().GetMember(enumValue.ToString())
                .FirstOrDefault()?
                .GetCustomAttribute<DisplayAttribute>()
                ?.GetDescription() ?? enumValue.ToString();
        return string.Empty;
   }

After doing this, our general coding is finished. Now if you add .GetDisplayDescription() to the end of your enum value while printing your model, we will achieve our goal.

An error has occurred. This application may no longer respond until reloaded. Reload 🗙