C# / .NETDevOpsMisc
C# / .NET
Get a string description from an enum
Alexandru Puiu
Alexandru Puiu
September 16, 2012
1 min

Enums can be very powerful when used appropriately, such as for populating fixed drop-down lists which almost never change

Let’s say you want to save a person’s gender in your database. You could save it as a string, but that’s very wasteful. Ideally you’d save it as tinyint, because it will never have more values, so why waste space and computing time with joins, or other solutions. Your enum could look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;

namespace Data.Enums
{
    public enum Genders : byte
    {
        [DescriptionAttribute("No Answer")]
        NoAnswer = 0,
        [DescriptionAttribute("Male")]
        Male = 1,
        [DescriptionAttribute("Female")]
        Female = 2
    }
}

Great, now you have an enum, but next how do you populate a drop-down list from it? The answer is simple. With the use of the following method, read the attributes from each value

public static string GetEnumString(Type enumtype, byte? selectedValue)
{
    string ret = "";
    if (selectedValue != null)
    {
        try
        {
            foreach (dynamic item in Enum.GetValues(enumtype))
                if ((byte)item == selectedValue)
                    ret = EnumUtils.stringValueOf(item);
        }
        catch { }
    }
    return ret;
}

Next, create a helper method to populate it for you, which you can re-use in every project

public static List GetGenders(byte selectedValue)
{
    List list = new List();
    foreach (Genders item in Enum.GetValues(typeof(Genders)))
        list.Add(new SelectListItem() {
            Text = EnumUtils.stringValueOf(item),
            Value = ((byte)item).ToString(),
            Selected = (byte)item == selectedValue });
    return list;
}

Tags

utils
Alexandru Puiu

Alexandru Puiu

Engineer / Security Architect

Systems Engineering advocate, Software Engineer, Security Architect / Researcher, SQL/NoSQL DBA, and Certified Scrum Master with a passion for Distributed Systems, AI and IoT..

Expertise

.NET
RavenDB
Kubernetes

Social Media

githubtwitterwebsite

Related Posts

RavenDB Integration Testing
Using RavenDB in Integration Testing
December 24, 2022
2 min

Subscribe To My Newsletter

I'll only send worthwhile content I think you'll want, less than once a month, and promise to never spam or sell your information!
© 2023, All Rights Reserved.

Quick Links

Get In TouchAbout Me

Social Media