At times I need to serialize my Lambda Expressions, to pass to some web service . Normally this wasn't possible but I realized the MetaLinq project allows it. MetaLinq actually grants us modifiable Expression trees. As you might now know Expression Trees are immutable just like strings. Anyway let's serialize and deserialize a Lambda expression within the code:
Expression<Func<int,int>> myLambda = z => z*z ;
// Create a mutable expression, we are using ExpressionBuilder namespace in MetaLinq here
var mutableExpression = ExpressionBuilder.EditableExpression.CreateEditableExpression(myLambda);
// Serialize it
var serializer = new XmlSerializer(typeof(EditableLambdaExpression));
var sw = new StringWriter();
serializer.Serialize(sw, mutableExpression);
// Get the lambda as string, actually sw.ToString() will give us it in string form
var sr = new StringReader(sw.ToString());
var anotherSerializer = new XmlSerializer(typeof(EditableLambdaExpression));
// Deserialize it
var myex = anotherSerializer.Deserialize(sr) as EditableExpression;
// Convert it to lambda expresion
var myNewLambda = myex.ToExpression() as LambdaExpression;
// Invoke it, outputs 16 as expected
Console.Write(myNewLambda.Compile().DynamicInvoke(4));
So this shows us how to convert an expression to string and restore back to expression and invoke it. DynamicInvoke used here since I assumed we don't know the type here. I hope you find it useful
Sunday, November 16, 2008
Subscribe to:
Posts (Atom)