Click here to Skip to main content
13,050,904 members (64,167 online)
Click here to Skip to main content
Add your own
alternative version


10 bookmarked
Posted 21 Oct 2006

Type Safe Role Names

, 21 Oct 2006
Rate this:
Please Sign up or sign in to vote.
A way to let the compiler stop you from mistyping role names.


It seems to me that using the Roles.XXX methods are prone to error because they take strings as arguments. You could mistype a string and be screwed. Even if you use a class that encapsulates the strings, you could still screw up by not using that class.

I propose using type safe wrapper functions to the Role.XXX functions.


First, define all your roles in an enum:

public enum Roles : int
    SuperAdmin = 0,

Then, define a RoleNames class like this:

public static class RoleNames
    private static readonly string[] _roles = Enum.GetNames(typeof(Roles));
    public static string Get(Roles r)
        return _roles[(int)r];

Finally, define wrapper classes like this:

public static void RemoveUserFromRole(string user, Roles role)
    Roles.RemoveUserFromRole(user, RoleNames.Get(role));

public static void AddUserToRoles(string user, Roles[] roles)
    List<STRING> rolestrings = new List<STRING>();

    foreach (Roles r in roles)

    Roles.AddUserToRoles(user, rolestrings.ToArray());

public static void AddUserToRole(string user, Roles role)
    Roles.AddUserToRole(user, RoleNames.Get(role));


Now when you write your code, the compiler will force a correct role name.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Web Developer
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170713.1 | Last Updated 21 Oct 2006
Article Copyright 2006 by aanodide
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid