views:

162

answers:

2

The code below works fine for primitive expressions (no surprise there)

public class SiteContextExpressionBuilder : ExpressionBuilder {
   public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) {
      PropertyInfo property = typeof(SiteContext).GetProperty(entry.Expression);
      return new CodePrimitiveExpression(property.GetValue(null, null)));
   }
}

Now I would like to return non primitive types as well. Let's say a Company object.
How does that work? I can't seem to find any good examples.

Invalid Primitive Type: ... Consider using CodeObjectCreateExpression

How do I implement the CodeObjectCreateExpression or alternative?

+1  A: 

I don't know what the constructor for your Company object looks like, so here's an example with Size:

Constructor

new Size(640, 400)

With CodeObjectCreateExpression

CodeExpression newSizeExpr = new CodeObjectCreateExpression(new CodeTypeReference(“System.Drawing.Size”),
   new CodePrimitiveExpression(640), new CodePrimitiveExpression(400));

If your Company constructor accepts primitive arguments, you can just use CodePrimitiveExpressions as in the above example. If it requires non primitive types, you can instantiate those non-primitive types with CodePrimitiveExpressions. Recurse until you have what you need to construct your Company object.

Update: Source may be helpful: http://blogs.msdn.com/bclteam/archive/2006/04/10/571096.aspx

chrissr
Thnx, but how do I use an existing instance? I have a couple of properties in a static class that I'd like to access with this technique.
Zyphrax
+1  A: 

You should have a look at the subclasses of CodeExpression, like CodePropertyReferenceExpression to use a property and CodeVariableReferenceExpression to get at the instance.

CodeExpressions are the low-level representation of language-agnostic statements and expressions. You have to decompose the equivalent C# statements to very primitive components.

Timores