C# / .NETSecurityDevOps
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,
        Male = 1,
        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)
            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;


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..



Social Media


Related Posts

Uploading Large Files
Upload Large Files in C#
September 21, 2020
4 min
© 2022, All Rights Reserved.

Quick Links

Get In TouchAbout Me

Social Media