Search code examples
c#enumsdefault-value

Enum not default to 0 when not defined


I have an enum type defined as follows:

public enum OperationTypeEnum : byte
{
    /// <remarks/>
    @__NONE = 0,

    /// <remarks/>
    Sale = 1,

    /// <remarks/>
    Auth = 2
}

In my code, I cast an integer like so:

var operationType = (OperationTypeEnum) anotherIntVariable;

When anotherIntVariable is something undefined (e.g. 5), I am hoping to get 0 or __NONE back (since 5 is not defined as one of the valid enum values, but I receive 5 instead.

What do I need to change to make undefined enum values to be 0?

Thanks!


Solution

  • C# enums are effectively integers and there are no compile or run time checks that you are using a "valid" value from your defined enum set. See this answer for more information https://stackoverflow.com/a/6413841/1724034