Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to guarantee the value of what ToString for an enum will be?

Tags:

c#

enumeration

The database I am working with currently has a varchar field, and in my code I want to map the potential values to a enumeration like:

public enum UserStatus
{
    Anonymous,
    Enrolled,
    SuperUser
}

At the database level for this column, there is a constrain on it where the value has to be:

ANONYMOUS
ENROLLED
SUPERUSER

Is it possible for me to do:

UserStatus.SuperUser.ToString()

And have that value be SUPERUSER, and this be consistant and not screw up down the road?

like image 951
loyalflow Avatar asked Dec 16 '13 20:12

loyalflow


People also ask

What happens if you ToString an enum?

ToString() Converts the value of this instance to its equivalent string representation.

How does enum ToString work?

The toString() method calls the name() method which returns the string representation of the enum constant. In listing 1, the value returned by calling the name() and toString() on an Animal. DOG constant method is DOG. public enum Animal { DOG } // Unit test assertThat(DOG.

How do you find the value of an enum?

Get the value of an Enum To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

How do you convert a string value to a specific enum type in C#?

TryParse() method converts the string representation of enum member name or numeric value to an equivalent enum object. The Enum. TryParse() method returns a boolean to indicate whether the specified string is converted to enum or not. Returns true if the conversion succeeded; otherwise, returns false .


2 Answers

A better solution may be to take advantage of the DescriptionAttribute:

public enum UserStatus
{
    [Description("ANONYMOUS")]
    Anonymous,
    [Description("ENROLLED")]
    Enrolled,
    [Description("SUPERUSER")]
    SuperUser
}

Then use something like:

/// <summary>
/// Class EnumExtenions
/// </summary>
public static class EnumExtenions
{
    /// <summary>
    /// Gets the description.
    /// </summary>
    /// <param name="e">The e.</param>
    /// <returns>String.</returns>
    public static String GetDescription(this Enum e)
    {
        String enumAsString = e.ToString();
        Type type = e.GetType();
        MemberInfo[] members = type.GetMember(enumAsString);
        if (members != null && members.Length > 0)
        {
            Object[] attributes = members[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (attributes != null && attributes.Length > 0)
            {
                enumAsString = ((DescriptionAttribute)attributes[0]).Description;
            }
        }
        return enumAsString;
    }

    /// <summary>
    /// Gets an enum from its description.
    /// </summary>
    /// <typeparam name="TEnum">The type of the T enum.</typeparam>
    /// <param name="description">The description.</param>
    /// <returns>Matching enum value.</returns>
    /// <exception cref="System.InvalidOperationException"></exception>
    public static TEnum GetFromDescription<TEnum>(String description)
        where TEnum : struct, IConvertible // http://stackoverflow.com/a/79903/298053
    {
        if (!typeof(TEnum).IsEnum)
        {
            throw new InvalidOperationException();
        }
        foreach (FieldInfo field in typeof(TEnum).GetFields())
        {
            DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (attribute != null)
            {
                if (attribute.Description == description)
                {
                    return (TEnum)field.GetValue(null);
                }
            }
            else
            {
                if (field.Name == description)
                {
                    return (TEnum)field.GetValue(null);
                }
            }
        }
        return default(TEnum);
    }
}

So now you're referencing UserStatus.Anonymous.GetDescription().

Of course you could always make your own DatabaseMapAttribute (or what-have-you) and create your own extension methods. Then you can kill a reference to System.ComponentModel. Completely your call.

like image 131
Brad Christie Avatar answered Sep 24 '22 01:09

Brad Christie


You can't override ToString for enums, instead you can create your own Extension Method like:

public static class MyExtensions
{
    public static string ToUpperString(this UserStatus userStatus)
    {
        return userStatus.ToString().ToUpper();// OR .ToUpperInvariant 
    }
}

And then call it like:

string str = UserStatus.Anonymous.ToUpperString();
like image 45
Habib Avatar answered Sep 25 '22 01:09

Habib