I’m experimenting with parsing expression trees and have written the following code:
private void TestExpressionTree()
{
Expression<Func<int, bool>> expression = x => x == 1 || x == 2;
string output = String.Empty;
HandleExpression(expression.Body, output);
Output("Output", output);
}
private void HandleExpression(Expression expression, string output)
{
switch (expression.NodeType)
{
case ExpressionType.Conditional:
HandleConditionalExpression(expression, output);
break;
case ExpressionType.OrElse:
HandleOrElseExpression(expression, output);
break;
case ExpressionType.Equal:
HandleEqualExpression(expression, output);
break;
case ExpressionType.Parameter:
HandleParameterExpression(expression, output);
break;
case ExpressionType.Constant:
HandleConstantExpression(expression, output);
break;
}
}
private void HandleConditionalExpression(Expression expression, string output)
{
ConditionalExpression conditionalExpression = (ConditionalExpression) expression;
HandleExpression(conditionalExpression.Test, output);
}
private void HandleOrElseExpression(Expression expression, string output)
{
BinaryExpression binaryExpression = (BinaryExpression)expression;
HandleExpression(binaryExpression.Left, output);
output += "||";
HandleExpression(binaryExpression.Right, output);
}
private void HandleEqualExpression(Expression expression, string output)
{
BinaryExpression binaryExpression = (BinaryExpression)expression;
HandleExpression(binaryExpression.Left, output);
output += "=";
HandleExpression(binaryExpression.Right, output);
}
private void HandleParameterExpression(Expression expression, string output)
{
ParameterExpression parameterExpression = (ParameterExpression)expression;
output += parameterExpression.Name;
}
private void HandleConstantExpression(Expression expression, string output)
{
ConstantExpression constantExpression = (ConstantExpression)expression;
output += constantExpression.Value.ToString();
}
The idea of the code is to parse the expression tree and write details about the nodes into the string variable output. However, when this variable is written to the page (using the Output() method), I’m finding it’s empty.
When I use the debugger to step through the code, I find that output is correctly set to ‘x’ when the code executes HandleParameterExpression() for the first time, but as soon as control returns from HandleParameterExpression() back to the switch block in HandleExpression(), the variable is mysteriously empty again.
Since strings are reference types, I should simply be able to pass the reference between the methods and changes to its value made by the methods should be retained, right? Is there some subtlety of parameter passing in C# that I’m not aware of?
You need to pass in ANY variable that you want to actually change by reference. So, in your example, you would need to do it this way:
And then when you call the function, you would do it this way: