RemarkLima
RemarkLima

Reputation: 12037

C# nameof into strongly typed parameter?

Using entity framework, I have an entity called permissions, which has a set of bools to specify what can and can't be done.

A little bit like:

public class Permissions
{
   public int Id {get;set;}
   public int GroupId {get;set;}
   public bool ViewRecords {get;set;}
   public bool EditRecords {get;set;}
   public bool DeleteRecords {get;set;}
   public bool CreateRecords {get;set;}
   public bool CreateSubGroups {get;set;}
}

You get the idea. Each user group has one of these and that's all good.

I have a security services class which validates and checks this information against the right group and action - again, all working well - however I'm left with some magic strings which I'd like to avoid.

For example: public bool HasPermission(int groupId, string action)

I'd like as: public bool HasPermission(int groupId, Permission action)

At the moment, I'm using nameof, so:

bool go = HasPermission(123, nameof(Permission.ViewRecords));

However, is there a way to map the class properties so it would be:

bool go = HasPermission(123, Permission.ViewRecords);

I could do it with an enum, and maintain the two to mirror each other, but that is an overhead I'd like to avoid - and whilst nameof works, the fact is the method can receive any string and therefore could be broken later down the line.

Upvotes: 1

Views: 257

Answers (2)

Peter B
Peter B

Reputation: 24147

I'd simply create a method GetPermission (if you don't have one yet):

Permissions GetPermission(int groupId) { ... }

and then use it like this:

if (GetPermission(123).ViewRecords) { ... }

Upvotes: 7

Rabban
Rabban

Reputation: 2581

This is not my code, but i can't remember from where i got it.

public bool HasPermission(int groupId, Expression<Func<T>> propertySelector)
{
    if (propertyExpresssion == null)
    {
        throw new ArgumentNullException("propertyExpresssion");
    }

    var memberExpression = propertyExpresssion.Body as MemberExpression;
    if (memberExpression == null)
    {
        throw new ArgumentException("The expression is not a member access expression.", "propertyExpresssion");
    }

    var property = memberExpression.Member as PropertyInfo;
    if (property == null)
    {
        throw new ArgumentException("The member access expression does not access a property.", "propertyExpresssion");
    }

    var getMethod = property.GetGetMethod(true);
    if (getMethod.IsStatic)
    {
        throw new ArgumentException("The referenced property is a static property.", "propertyExpresssion");
    }

    var name = memberExpression.Member.Name;
}

You can call it with:

bool go = HasPermission(123, () => Permission.ViewRecords);

Upvotes: 1

Related Questions