Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte enum comparison in C#

Tags:

c#

enums

Given this enum

public enum UserStatus : byte
{
    Approved = 1,
    Locked = 2,
    Expire = 3
}

why does this check always return false when usr.Status = 1

if(usr.Status.Equals(UserStatus.Approved))
    return true;
return false;

The comparison seems to work - there is no compile time error or runtime exception. Please note I am not the author of this piece of code and would like to find out why the author chose enum of type byte and why this doesn't work as it should.

like image 815
mare Avatar asked Jul 06 '11 12:07

mare


People also ask

Can we compare enum values in C?

How to compare Enum values in C#? Enum. CompareTo(Object) Method is used to compare the current instance to a specified object and returns an indication of their relative values.

Is an enum a byte?

The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.

How do you change the size of an enum?

The size of an enum is compiler-specific and should default to the smallest integral type which is large enough to fit all of the values, but not larger than int. In this case, it seems the sizeof enum is fixed at 16-bit.


1 Answers

Because you will have to cast.

The equals method will check if UserStatus is an int (depending on the type you have defined at the property usr.Status). It will then return that is not (it is of type UserStatus) thus return false

Better code would be:

return usr.Status == (int)UserStatus.Approved;
like image 112
Oskar Kjellin Avatar answered Oct 02 '22 10:10

Oskar Kjellin