0

I have a real banged up API where the return values using naming conventions that are all over the place… From camelCase to PascalCase to UPPERCASE to string with spaces… it’s a mess…

So in order to serialize or deserialize it, using json.net is simple enough adding a jsonSerializer or adding a class with json property attributes as so:

[JsonProperty(PropertyName = "somebanged upName")]
public string[] SomethingBangedUp;

I would also like to do a similar thing when hardtyping some values to an enum, and then get a list of the ‘banged up names’ rather than the variable names:

public enum SomeBangedUpEnum
{
    [EnumMember(Value = "someThingelse BangedUp")]
    SomethingElseBangedUp,
}

var v = Enum.GetNames(typeof(SomeBangedUpEnum)).ToList();

But this retrives the variable name of “SomethingElseBangedUp” and not “someThingelse BangedUp” as i hoped for;

Any idea how I can get the banged up value set by the EnumMember attribute?

axa
  • 428
  • 6
  • 19
  • 1
    See here: http://stackoverflow.com/a/1415187/5311735. Also, use something like `Description` attribute (from System.ComponentModel namespace). EnumMember is related to serialization and is completely alien here (even if it's name suggests otherwise). – Evk Apr 13 '17 at 20:28
  • This is good info... though how might i adjust said answer to retrieve all with this description attribute... (and then the normal variable names for those without any attribute) – axa Apr 13 '17 at 20:45

1 Answers1

1

Attributes are metadata. If you want to read metadata, you should use reflection. You can use GetCustomAttribute extension to read attribute value from type member. E.g. if you want to get all names for enumeration members:

var v = typeof(SomeBangedUpEnum)
   .GetFields(BindingFlags.Public|BindingFlags.Static)
   .Select(f => f.GetCustomAttribute<EnumMemberAttribute>()?.Value)
   .ToList();

Or if you want to get name for some specific enum member, then instead of getting all fields you can get specific field only:

var name = typeof(SomeBangedUpEnum)
    .GetField(SomeBangedUpEnum.SomethingElseBangedUp.ToString())
    .GetCustomAttribute<EnumMemberAttribute>()?.Value;
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
  • why might EnumMemberAttribute not be recognized for me? – axa Apr 13 '17 at 20:39
  • @axa you should add using for `System.Runtime.Serialization` namespace as well as for `System.Reflection` namespace – Sergey Berezovskiy Apr 13 '17 at 20:41
  • All is fine but it makes little sense to use EnumMember attribute for this - it is in separate assembly, it is related to serialization, and there is no serialization here. Maybe better is to use Description attribute from System.ComponentModel. But that is nitpicking of course. – Evk Apr 13 '17 at 20:48
  • @Sergey Berezovskiy but i do... and i have a Reference added to the project... is this available in a later .net than 4.5.2? – axa Apr 13 '17 at 21:06