Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum set to string and get sting value when need

Tags:

string

c#

enums

I don't know how to do this
I want code like following

enum myenum
{
    name1 = "abc",
    name2 = "xyz"
}

and check it

if (myenum.name1 == variable)

how can I do those things?

thanx.

like image 537
Darshana Avatar asked May 03 '12 06:05

Darshana


People also ask

Can we give string value in enum?

This can be accomplished easily by using the DescriptionAttribute class. Originally, I was using code like the following to set the string value based on the value of an enum, but it seemed too cumbersome and had to be used everytime I wanted to parse an enum.

How do I convert an enum to a string?

There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.

What happens if you toString an enum?

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

Can enums store strings?

Enum constants can only be of ordinal types ( int by default), so you can't have string constants in enums.


2 Answers

Unfortunately that's not possible. Enums can only have a basic underlying type (int, uint, short, etc.). If you want to associate the enum values with additional data, apply attributes to the values (such as the DescriptionAttribute).

public static class EnumExtensions
{
    public static TAttribute GetAttribute<TAttribute>(this Enum value)
        where TAttribute : Attribute
    {
        var type = value.GetType();
        var name = Enum.GetName(type, value);
        return type.GetField(name)
            .GetCustomAttributes(false)
            .OfType<TAttribute>()
            .SingleOrDefault();
    }

    public static String GetDescription(this Enum value)
    {
        var description = GetAttribute<DescriptionAttribute>(value);
        return description != null ? description.Description : null;
    }
}

enum MyEnum
{
    [Description("abc")] Name1,
    [Description("xyz")] Name2,
}

var value = MyEnum.Name1;
if (value.GetDescription() == "abc")
{
    // do stuff...
}
like image 173
Jeff Mercado Avatar answered Oct 24 '22 01:10

Jeff Mercado


According to here what you are doing is not possible. What you could do maybe would be to have a static class full of constants, maybe something like so:

class Constants
{
    public static string name1 = "abc";
    public static string name2 = "xyz";
}

...

if (Constants.name1 == "abc")...
like image 23
npinti Avatar answered Oct 24 '22 03:10

npinti