Alexandru Chichinete
Alexandru Chichinete

Reputation: 1182

Pass an Enum as parameter in DynamicExpression

I am using ParseLambda from System.Linq.DynamicExpression namespace. More info can be found on ScottGu's blog.

The following code throws Unknown identifier 'TeamType' exception

public bool CheckCondition()
{
    try
    {
        var condition = "CurrentUser.CurrentTeamType == TeamType.Admin";
        var currentUserParameter = Expression.Parameter(typeof(UserInfo), "CurrentUser");
        var dynamicExpression = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { currentUserParameter}, null, condition);
        var result = dynamicExpression.Compile().DynamicInvoke(CurrentUserInfo);
        return Convert.ToBoolean(result);
    }
    catch(Exception ex)
    {
      // do some stuff then throw it again
      throw ex;
    }
}

public enum TeamType
{
    Admin = 1,
    AnotherType = 2
}

public class UserInfo
{
    public short UserId { get; set; }
    public string UserName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public TeamType CurrentTeamType { get; set; }
}

CurrentUserInfo is just an instance of UserInfo;

My question is what can I do so TeamType will be recognized, or how can I pass the enum as parameter.

Additional exceptions:

If I change condition to Convert.ToInt32(CurrentUser.CurrentTeamType) == 1, I get the following exception Expression of type 'Namespace.TeamType' cannot be used for parameter of type 'System.Object' of method 'Int32 ToInt32(System.Object)'

If I change condition to (int)CurrentUser.CurrentTeamType == 1, I get the following exception Unknown identifier 'int'

If I add namespace too like var condition = "CurrentUser.CurrentTeamType == App.BE.TeamType.Admin";, I get Unknown identifier 'App'. Please note that I have a reference to App.BE namespace

Upvotes: 1

Views: 999

Answers (2)

creo
creo

Reputation: 49

There is much easier solution - just use text representation of enum value, i.e. this will work:

var condition = "CurrentUser.CurrentTeamType == \"Admin\"";

Upvotes: 0

Dan Friedman
Dan Friedman

Reputation: 5228

Try using the full namespace to TeamType. Since you are using it in a string, it probably just needs you to be more specific.

UPDATE:

I think this answer will help you. You need to set up predefined types ahead of time.

Upvotes: 1

Related Questions