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'
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'
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 c# enums
You are not signed in. Login or sign up in order to post.
You can’t, enums are numbers, not strings.
– Jéf Bueno
@jbueno, I know that, so I asked how I do to have an Enum similar to the one obtained in the post.
– pnet
When I need something like this, I use the
Description
ofenum
. Look at this question How to recover the description of an enumerator? how do I do.– Pedro Camara Junior