Get Enum Description According to language culture or resource file in C#

By 8th February 2019ASP.NET, C#, MVC

if i have an enum and i want to show the description on view or in dropdown than, than we can change the description according to resource language file.

Full example below:

We have an Enum First

public enum MeetingType
        {
            [Description("Booked Meeting")]
            APPOINTMENTBOOKED = 1,
            [Description("Prescription Bookings")]
            MEETINGWITHPRESCRIPTIONRENEWAL = 2,
            [Description("Prescription Renewal")]
            PRESCRIPTIONRENEWAL = 3
        }

And then we will add these description strings in our resource files.

After Adding strings or key in resource file we have created a extension method for further use.

First import

using System.Resources;

public static string GetDisplayName(this Enum e)
        {
            var rm = new ResourceManager(typeof(DoctorPanel.Resources.Resource));
            var resourceDisplayName = rm.GetString(ExtensionMethod.EnumDescription(e).Replace(" ",string.Empty));

            return string.IsNullOrWhiteSpace(resourceDisplayName) ? string.Format("[[{0}]]", e) : resourceDisplayName;
        }

And use this method where you want to get enum description according to resource or language wise.

var GetString=YourEnum.GetDisplayName();

we used white space remover because, Resource file keys accept without spaces or you can write your enum description without spaces.

 

Leave a Reply