How to get the integer value of one of the constants of an enum?

8

I have an enum (enumeration) calling Notas and I need to get the integer corresponding to one of its constants.

public enum Nota
{
    Otimo = 5,
    MuitoBom = 4,
    Bom = 3,
    Regular = 2,
    Ruim = 1,
    Insuficiente = 0
}

I tried the following, but I did not succeed:

Aluno aluno = new Aluno();
aluno.Nota = Nota.MuitoBom;

The property Conceito is integer type and even then I can not get the integer value of the Nota.MuitoBom constant, since the compiler says that it can not implicitly convert type Nota to int .     

asked by anonymous 15.12.2013 / 03:22

2 answers

6

You can get the expected result by performing a cast cast since the data are of different types ( Nota and int ). Just use the cast / cast operator with the type of data you want, in which case it would be int .

aluno.Nota = (int)Nota.MuitoBom;
    
15.12.2013 / 03:22
8

If you are manipulating the enum of typed , as type Nota , a simple cast is enough:

public static void ImprimirNotaComoInteiro(Nota nota)
{
    Console.WriteLine((int)nota);
}

Now, if you are manipulating like System.Enum , use the Convert.ToInt32 (since simple cast conversion is not possible):

public static void ImprimirEnumComoInteiro(Enum valorEnum)
{
    Console.WriteLine(Convert.ToInt32(valorEnum));
}
    
15.12.2013 / 03:36