Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Enum name based on the Enum value

I have declared the following Enum:

public enum AfpRecordId
{
    BRG = 0xD3A8C6,
    ERG = 0xD3A9C6
}

and i want to retrieve the enum object from is value:

private AfpRecordId GetAfpRecordId(byte[] data)
{
    ...                    
}

Call Examples:

byte[] tempData = new byte { 0xD3, 0xA8, 0xC6 };
AfpRecordId tempId = GetAfpRecordId(tempData);

//tempId should be equals to AfpRecordId.BRG

I would also like to use linq or lambda, only if they can give better or equals performance.

like image 765
Duncan_McCloud Avatar asked Nov 02 '11 11:11

Duncan_McCloud


2 Answers

Simple:

  • Convert the byte array into an int (either manually, or by creating a four byte array and using BitConverter.ToInt32)
  • Cast the int to AfpRecordId
  • Call ToString on the result if necessary (your subject line suggests getting the name, but your method signature only talks about the value)

For example:

private static AfpRecordId GetAfpRecordId(byte[] data)
{
    // Alternatively, switch on data.Length and hard-code the conversion
    // for lengths 1, 2, 3, 4 and throw an exception otherwise...
    int value = 0;
    foreach (byte b in data)
    {
        value = (value << 8) | b;
    }
    return (AfpRecordId) value;
}

You can use Enum.IsDefined to check whether the given data is actually a valid ID.

As for performance - check whether something simple gives you good enough performance before you look for something faster.

like image 195
Jon Skeet Avatar answered Sep 18 '22 08:09

Jon Skeet


Assuming that tempData has 3 elements use Enum.GetName (typeof (AfpRecordId), tempData[0] * 256*256 + tempData[1] * 256 +tempData[2]).

like image 29
Yahia Avatar answered Sep 19 '22 08:09

Yahia