Doubt when declaring Enum with string

Asked

Viewed 781 times

2

numDeclarate an Enum type string, like this:

public enum SEXO
{
    M = "Masculino",
    F = "Feminino"
}

As I do to have an Enum similar to the one above. That way give error:

Cannot implicitly Convert type 'string' to 'int'

1 answer

3


You can’t, at least not directly the way you’re trying to ask the question.

You can achieve a similar effect using extensions, take the example

public static string GetStringValue(this Enum value)
{
    var type = value.GetType();

    var fieldInfo = type.GetField(value.ToString());

    var attributes = fieldInfo.GetCustomAttributes(
        typeof(StringValueAttribute), false) as StringValueAttribute[];

    var stringvalue = attributes != null && attributes.Length > 0 ? attributes[0].StringValue : value.ToString();
    return stringvalue;
}

public class StringValueAttribute : Attribute
{
    public string StringValue { get; protected set; }

    public StringValueAttribute(string value)
    {
        StringValue = value;
    }
} 

Enum’s statement

public enum Sexo
{
    [StringValue("Masculino")]
    M = 1,    
    [StringValue("Feminino")]
    F = 2
}

Use

string descrEnum = Sexo.M.GetStringValue();

I vaguely remembered that this code had come out of here from Sopt, now I found little him in this answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.