Click here to Skip to main content
15,889,868 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have enumeration like this:
C#
 public enum returnCodes
        {

            Success = 0,
            Timeout = 1,
            GeneralReject = 0x10,
            ServiceNotSupported = 0x11,
            SubFunctionNotSupported = 0x12,
            InvalidMessageLength = 0x13,
            BusyRepeatRequest = 0x21
}


I have a result that is byte array. I want to check if 3rd byte out there is among any of the values in enumeration. If yes then display some message.
For that i can individually check each value like this:
C#
if (_receivedFrame.Data[2] == (int)returnCodes.GeneralReject)
           {
               MessageBox.Show("first");
           }
           else if (_receivedFrame.Data[2] == (int)returnCodes.Success)
           {
               MessageBox.Show("second");
           }


But i want to know if there is any efficent way of coding where i can compare 3rd byte with all values in enumaration.
Posted

I wrote a tip/trick for this:

Setting Enumerators From Questionable Data Sources (for C# and VB)[^]

You would use it this way:

C#
if (IntToEnum(_receivedFrame.Data[2], returnCodes.GeneralReject) == returnCodes.Success)
{
    // do something

}
 
Share this answer
 
v2
Comments
Rick Shaub 14-Sep-11 9:22am    
Good tip. I was going to mention Enum.IsDefined, but it looks like you got it covered.
glued-to-code 15-Sep-11 2:33am    
Thanks for this answer, but i wanted a way wherein we can compare 3rd byte to all enum values available. like comparing 3rd byte to firste num value, second enum value.. to the last enum value. If none of the enum values matches 3rd byte, it should not do anything, otherwise it should return the particular enum value
You could use Enum.GetValues :
C#
var enumValues = Enum.GetValues(typeof(returnCodes));
foreach (object enumValue in enumValues)
{
   if((returnCodes)enumValue == _receivedFrame.Data[2])
   {
       //Do something
   }
}


Alternately, you could load a Dictionary in the static constructor and just look up the string to return.
 
Share this answer
 
Comments
glued-to-code 16-Sep-11 5:26am    
Thank you very much!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900