Introduction
This snippet of code allows me to use classes and treat them like enums (to a certain extent). Since it is based on a class type paradigm, this allows me to introduce other properties as well.
Also, I'd like to mention that this is my first article written and published on the web, not much of a blogger, but I do like helping out other fellow coders.
Background
A few months ago I came across this CP article a few months ago and found it quite interesting. So I basically took this code and ran with it.... Or so the expression goes.
Like to thank Cassio Mosqueira for giving me a head start on this enum snippet idea; hope you find it rather useful.
Using the code
Think that using this code is pretty simple and straight forward to use. Since enum style is taking an OOP approach, we must first inherit from
Enum<T>
.
Like so:
public class UserRole : Enum<UserRole>
{
public static readonly UserRole
Guest = new UserRole(0x02, "Guest"),
User = new UserRole(0x04, "User"),
Admin = new UserRole(0x0c, "Admin"),
Super = new UserRole(0x1c, "Super");
public UserRole(int key, string value) : base(key, value) { }
}
Then we can use something like so
EnumCollection<UserRole> roles = UserRole.GetBaseOrKey(0x1c); bool isguest = roles == UserRole.Guest; bool isnotguest = roles > UserRole.Guest; bool isadmin = (roles & UserRole.Admin) == UserRole.Admin; roles = UserRole.Admin; string str = roles.ToString();
str = UserRole.Admin.Value;
str = UserRole.Admin;
int int32 = UserRole.Admin;
Pretty simple to use.
Points of Interest
Not gonna lie. It was fun coding this. One thing I did not test for was performance, not really sure how well this is going to test out
when this is added on a larger project. But for small ones, seems kind of fun.
I
have attached the source code and not the solution. Figure you can always just drop
it into your project and run with it.
History
2/1 - Original version released.