2

I want to parse a binary file.

I have 3 valid formats. in the binary file the format is represented by short. but it can be only 0,1,2

I created enum to describe these formats.

When i wrote this code i saw this compiler error:

Operator '>' cannot be applied to operands of enum and int.

    public enum FormatType
    {
        Type0 = 0,
        Type1 = 1,
        Type2 = 2
    }

    private FormatType _format;
    public FormatType Format
    {
        get { return _format; }
        set
        {
            // red line under value > 2.
            if (value < 0 || value > 2) throw new FileParseException(ParseError.Format);
            _format = value;
        }
    }

but there is no problem with value < 0.

later i find out that i can compare enum with 0 but not with other numbers.

simply to fix this problem i can cast int to enum.

value > (FormatType)2

But no need to cast when comparing with 0 why?

value < 0
M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
  • 2
    Are you looking for `Enum.IsDefined(typeof(FormatType), value)`? -- see [Enum.IsDefined](https://msdn.microsoft.com/library/vstudio/system.enum.isdefined.aspx) – Corak Jul 15 '15 at 08:32
  • thanks for this suggestion. i didnt know i can check existence of enum like this. i used it but my question still remains! @Corak – M.kazem Akhgary Jul 15 '15 at 08:35
  • 2
    Maybe this will help: [Implicit Zero To Enum Conversion](http://geekswithblogs.net/BlackRabbitCoder/archive/2012/01/26/c.net-little-pitfalls-implicit-zero-to-enum-conversion.aspx) --- which more or less points to: [6.1.3 Implicit enumeration conversions](https://msdn.microsoft.com/library/aa691283.aspx) which states: "An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type." – Corak Jul 15 '15 at 08:36
  • thanks for the comments and links. i thought the problem was operator. but it was implicit conversion of 0 @Corak – M.kazem Akhgary Jul 15 '15 at 08:42

1 Answers1

2

you need to cast the enum to int where you are using it as an int:

    public FormatType Format
    {
        get { return _format; }
        set
        {
            // red line under value > 2.
            if (value < 0 || (int)value > 2) throw new FileParseException(ParseError.Format);
            _format = value;
        }
    }

Edit: literal zero will always be implicitly convertible to any enum to ensure your are able to initialize it to its default value (even if there is no enum with value 0)

Found these links that explain it better:

http://blogs.msdn.com/b/ericlippert/archive/2006/03/29/the-root-of-all-evil-part-two.aspx http://blogs.msdn.com/b/ericlippert/archive/2006/03/28/563282.aspx

raduchept
  • 181
  • 4
  • 11