Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Enums on steroids

0.00/5 (No votes)
1 Feb 2013 1  
If enums' could be used OOP style.

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   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); // Retrieves a collection of User, Admin, Super
bool isguest = roles == UserRole.Guest;                       // Compare if roles is just Guest
bool isnotguest = roles > UserRole.Guest;                     // Compare if is an authenticated user 
bool isadmin = (roles & UserRole.Admin) == UserRole.Admin;    // Compare if user is admin    
roles = UserRole.Admin;                                       // Role is just 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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here