Comparing bytes with enumeration in C #

Given this listing

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

why this check always returns 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 that I am not the author of this piece of code and would like to know why the author chose an enumeration of type byte and why this does not work as it should.

+6
source share
3 answers

Because you have to quit.

The equals method checks if UserStatus int (depending on the type specified in the usr.Status property). Then it will return it not (this is a UserStatus type), so return false

Best code:

 return usr.Status == (int)UserStatus.Approved; 
+9
source

The first thing that the Equals check usually does is "this is the correct type." And UserStatus does not match with byte .

(in fact, this happens only because you placed objects through the incompatible use of Equals ; at the IL level, they are indistinguishable until they are boxed)

You must compare them as objects of the same type. Take some code from byte :

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

This is because Usr.Status contains Integer, and UserStatus.Approved returns String ie, Approved . Thus, the integer value 1 cannot be equal to String Approved . Thus, you must convert the status of Enum also to an integer using the following code

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

Source: https://habr.com/ru/post/892128/


All Articles