Does not accept Enum parameter with non-zero integer

Asked

Viewed 86 times

2

Follows code:

class Program
{
    public enum Enum
    {
        Casa = 0,
        Apartamento = 5
    }

    public static string MinhaFuncao(Enum @enum) => "MinhaFuncao";
    static void Main(string[] args)
    {    
        var r = MinhaFuncao(0);
    }
}

Why can’t I put for example: MinhaFuncao(5);?

The zero integer (0) accepts, now other than zero (1, 2, 3...) does not accept.

I get error:

Cannot convert from "int" to "Console.Program.Enum".

1 answer

2


In fact you should not accept any number, after all an integer is a value of a type and you expect a value of an enumeration, which case has integers with subliminal values.

Doubt remains because 0 is accepted. I believe that is because that is the value default of the enumeration. It is a value that is always accepted, so it will always work, even if you do not have a member with that value. For the others he would have to check if the number matches any member and this check can only be made at execution time goes against what C# preaches, so he prefers to give error.

  • Can you avoid zero integer in the ? parameter Enum.Casa, without using a whole number.

  • No, that’s one of the flaws of enum of C#, one of the most criticized features of language.

Browser other questions tagged

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