3

In my code I make use of many small enums:

enum UserRequest : byte { Burp=1, Sneeze=2, Fart=3 }

I often need to validate integer input before converting it to this enum.

bool valid_input = Enum.IsDefined(typeof(UserRequest), user_byte_value);

This approach does not work when the enum makes use of the FlagsAttribute; Enum.IsDefined cannot automatically combine flags to make a specified value. However, I've been able to work around not needing FlagsAttribute.

However, TIL that Eazfuscator.NET's obfuscation breaks Enum.IsDefined. I knew it was a possibility, but I was hoping it wouldn't since it's not in the System.Reflection namespace (reportedly though, it makes heavy use of System.Reflection).

So I'm wondering if anyone knows any good alternatives. I'm specifically after the following:

  1. Allows checking if an integer is in a specified enum.
  2. Compatible with .NET Framework 2.0 and the Mono Framework.
  3. Survives obfuscation without explicitly disabling it (using attributes or some GUI tool).
ogggre
  • 2,204
  • 1
  • 23
  • 19
Mr. Smith
  • 4,288
  • 7
  • 40
  • 82
  • 2
    There are constant questions about "Eazfuscator breaks my code". Usually with "they are not responding". Ditch it. – Hans Passant Apr 28 '12 at 00:21
  • @HansPassant IIRC, some of the other obfuscators I've used don't break Enum.IsDefined(), but I don't blame Eazfuscator. I might go with a solution involving, what I think is called, 'enum guards'. The idea is you do something like this: enum UserRequests : byte { Burp=0,Sneeze=1,Fart=2,MAXVAL=3 } And you can check if a specified integer is in the flag by comparing it to MAXVAL. – Mr. Smith Apr 28 '12 at 00:27
  • Try [Crypto Obfuscator](http://www.ssware.com/cryptoobfuscator/obfuscator-net.htm). It has some intelligent auto-exclusion rules for enum based scenarios. DISCLAIMER: I work for LogicNP Software, the developer of Crypto Obfuscator. – logicnp Aug 09 '12 at 09:20
  • Try no obfuscator. It makes you programs work just as intented. – Uwe Keim Dec 15 '12 at 12:01

1 Answers1

2

In the event others run into this same problem, and find this article, the solution I went with was to add an additional enum member to each of my enums.

enum UserRequests : byte
{
    Burp = 0,
    Sneeze = 1,
    Fart = 2,
    /* Maximum Valid Value */
    MAXVAL = Fart
}

This is a practice I remember using in C ((non-ANSI) with #defines) to iterate over enum values, its only downside is that it's hard to maintain.

I wrote a generic function to lesson the burden (header shown below); I still have to explicitly pass the MAXVAL member, but it's less work than I thought. And of course, it survives obfuscation and is portable.

public static bool TryParseByteToEnum<T>(byte input_byte, 
    out T enum_member, T max_value) where 
        T : struct, IConvertible
Mr. Smith
  • 4,288
  • 7
  • 40
  • 82