Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if byte is a value from enum

This is my enum:

internal enum ServiceCode
{
    AAA = 0x54, BBB = 0x24, CCC = 0x45
};

In my method, I want to check, if the byte number is in my enum:

Byte tByteItem;

// tByteItem converted to decimal for example: 0x54 -> 84

// now I want to check, if 84 (=0x54) is in my enum
// it should be true, because AAA = 0x54 = 84
if (Enum.IsDefined(typeof(ServiceCode), tByteItem))
{
    // ...          
}

My if clause doesn't work, how can I do that?

like image 320
Stampy Avatar asked Oct 21 '25 11:10

Stampy


2 Answers

I'm guessing that The reason that Enum.IsDefined isn't working is because you're it performs a type check to ensure that the value that you're passing matches the base type of the Enum. In this case, since you didn't specify, the base type is int.

You're passing it a byte rather than an int, which means that the type check fails and throws an Exception. You could try simply casting your byte to an int when calling the method which should take care of the issue:

if(Enum.IsDefined(typeof(ServiceCode), (int)tByteItem))
{
    //..
}

You could also try changing the underlying type of the Enum to byte, which would limit the available values for later:

internal enum ServiceCode : byte
{
    AAA = 0x54,
    BBB = 0x24,
    CCC = 0x45
}

Or, if that still doesn't work, you could try an alternate method. Something like:

// Get all possible values and see if they contain the byte value.
if(Enum.GetValues(typeof(ServiceCode).Contains(tByteItem))
{
    //...
}

Which is obviously less than ideal, but could get you through in a pinch.

like image 199
Justin Niessner Avatar answered Oct 24 '25 01:10

Justin Niessner


When you don't specify your enum, the base type of an Enum is an integer. By deriving it from byte, this might work:

internal enum ServiceCode : byte {
    AAA = 0x54,
    BBB = 0x24,
    CCC = 0x45
}

Then you can simply use:

Enum.IsDefined(typeof(ServiceCode), (byte) 0x54);//true
Enum.IsDefined(typeof(ServiceCode), (byte) 0x84);//false

(tested on the csharp interactive shell of mono)


Note this has some side effects: it is for instance impossible to assign a value 0x1234 to an enum member (since a boolean can only reach values between 0x00 and 0xff).


This is because C# does not really "use" the notion of an Enum. Internally the enums are stored by their binary value, and if necessary (e.g. ToString() method) special methods are used. In that sense enums in C# are less object-oriented than their java counterparts.

like image 23
Willem Van Onsem Avatar answered Oct 24 '25 02:10

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!