Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Check for attribute's existence on enum's element

I've got a situation like the following:

enum Header
{
    Sync,
    [OldProtocol] Keepalive,
    Ping,
    [OldProtocol] Auth,
    [OldProtocol] LoginData
    //...
}

I need to obtain an array of elements on which the OldProtocolAttribute is defined. I've noticed that the Attribute.IsDefined() method and its overloads apparently don't support this kind of situation.

My question is:

  • Is there a way to solve the problem without using in any part of the solution typeof(Header).GetField()?
  • If not, what's the most optimal way to solve it?
like image 721
user1098567 Avatar asked Jan 07 '12 17:01

user1098567


1 Answers

As far as I'm aware, you have to get the attribute from the field. You'd use:

var field = typeof(Header).GetField(value.ToString());
var old = field.IsDefined(typeof(OldProtocolAttribute), false);

Or to get a whole array:

var attributeType = typeof(OldProtocolAttribute);
var array = typeof(Header).GetFields(BindingFlags.Public |
                                     BindingFlags.Static)
                          .Where(field => field.IsDefined(attributeType, false))
                          .Select(field => (Header) field.GetValue(null))
                          .ToArray();

Obviously if you need this often, you may well want to cache the results.

like image 154
Jon Skeet Avatar answered Sep 22 '22 10:09

Jon Skeet