Click here to Skip to main content
Click here to Skip to main content

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.

Introduction

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.

Implementation

First, define all your roles in an enum:

public enum Roles : int
{
    SuperAdmin = 0,
    TrialNeedsActivation,
    Trial,
    Admin,
    Operator
}

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)
    {
        rolestrings.Add(RoleNames.Get(r));
    }

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

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

Conclusion

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

License

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

About the Author

aanodide
Web Developer
United States United States
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web03 | 2.8.140709.1 | Last Updated 21 Oct 2006
Article Copyright 2006 by aanodide
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid