mare
mare

Reputation: 13083

Byte enum comparison in C#

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.

Upvotes: 14

Views: 39422

Answers (3)

That is because the Usr.Status contains an Integer and the UserStatus.Approved returns an String i.e., Approved. So, an integer of value 1 can not be equal to the String Approved. So, you must convert the Enum status also to an integer by the following code

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

Upvotes: 0

Oskar Kjellin
Oskar Kjellin

Reputation: 21900

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;

Upvotes: 16

Marc Gravell
Marc Gravell

Reputation: 1064184

The first thing any Equals implementation usually checks is: "is this the right type". And UserStatus is not the same as byte.

(actually, this only happens because you have boxed the items via your incompatible use of Equals; at the IL level they are indistinguishable until boxed)

You must compare them as items of the same type. To borrow some code from byte:

public override bool Equals(object obj)
{
    return ((obj is byte) && (this == ((byte) obj)));
}

Upvotes: 8

Related Questions