Search code examples
c#expression-trees

How to access a property which is a class using Expressions


I have a class called "User" which has a property defined as a class "Department" (i also want to know what is it called, LOL). I want to access the property in the "Department" class called "Name" (User.Department.Name). It throws a NulLReferenceException when I input the arguement into the compiled expression.

I have this code below. Thanks in advance.

        ParameterExpression paramExpr = Expression.Parameter(typeof(User), "user");
        MemberExpression depPropExpr = MemberExpression.Property(paramExpr, "Department");
        MemberExpression depNamePropExpr = MemberExpression.Property(depPropExpr, "Name");
        ConstantExpression constantExpression = Expression.Constant("SBCA");

        var expression = Expression.Assign(depNamePropExpr, constantExpression); var compiledExpression = Expression.Lambda<Action<User>>(expression, new[] { paramExpr }).Compile();
        compiledExpression(user);

Solution

  • As you can see in this .NET Fiddle your code works fine.

    public class Program
    {
    
        public static void Main()
        {
            var user = new User();
            user.Department = new Department();
            user.Department.Name = "hello";
            Console.WriteLine("Before: " + user.Department.Name);
    
            ParameterExpression paramExpr = Expression.Parameter(typeof(User), "user");
            MemberExpression depPropExpr = MemberExpression.Property(paramExpr, "Department");
            MemberExpression depNamePropExpr = MemberExpression.Property(depPropExpr, "Name");
            ConstantExpression constantExpression = Expression.Constant("SBCA");
    
            var expression = Expression.Assign(depNamePropExpr, constantExpression);
    
            var compiledExpression = Expression.Lambda<Action<User>>(expression, new[] { paramExpr }).Compile();
            compiledExpression(user);
            Console.WriteLine("After: " + user.Department.Name);
        }
    }
    
    public class User
    {
        public Department Department { get; set; }
    }
    
    public class Department
    {
        public string Name { get; set; }    
    }
    

    Output:

    Before: hello
    After: SBCA

    The problem (the NullReferenceException) is that user.Department is null, where your expression is doing user.Department.Name = "SBCA";.
    You can test this by removing the assignment of user.Department = new...