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

Asked

Viewed 2,353 times

8

I have an Enum (enumeration) calling Notas and need to obtain 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 was unsuccessful:

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

The estate Conceito is of the whole type and yet I cannot take the whole value of the constant Nota.MuitoBom, because the compiler says you can’t implicitly convert the type Nota for int.

  • 1

    Can you add the exact error message reported by the compiler? (And I think you got confused by including the answer in the question. The codes are the same)

2 answers

8

If you’re manipulating the Enum in a way tipada, like the guy Nota, just a simple cast:

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

Now, if you’re manipulating like System Enum, use the method Convert.Toint32 (since conversion via simple cast is not possible):

public static void ImprimirEnumComoInteiro(Enum valorEnum)
{
    Console.WriteLine(Convert.ToInt32(valorEnum));
}

6


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

aluno.Nota = (int)Nota.MuitoBom;

Browser other questions tagged

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