I’ve been converting a Java crypto library to C#, and in the course of my work, I’ve found that the library makes heavy use of enumerations that have string values. Now, I’ve been trying to keep the APIs as similar as possible—although I think it would probably be better in the long run if both the Java and C# libraries (and the C++ library, and any others we may make in the future) were refactored into a language-agnostic way. But that’s for another day. So, trying to follow the interfaces specified in the Java library, I’ve had to find a way to simulate string enums in C# (which doesn’t have them).
In searching for a way to do this, and being new to C#, I found this post by Wayne Hartman. This doesn’t provide all of the benefits of Java enums, but it can get you by in a lot of circumstances. (There was one place it wouldn’t work for me, so I had to resort to using a class in that case.) Basically, you use the System.reflection and System.ComponentModel namespaces and add some metadata to your enums. Then you write a little class that can access them.
It’s not as good as Java enums, but it will work for basic string-valued enums.

0 comments:
Post a Comment