Lambdas / Anonomous delegates

Nice little trick when working with Expression API

So I like writing Expression tree API magic, but I am mortal and don’t find it that easy to do, and it normally takes me a while to do this. So I am up for any help that I can get.

I just learnt a neat little trick, which is that you can apply TypeDescriptor attributes at runtime, which is cool. This one thing allows us to use a fairly standard PropertyGrid to visualize Expression trees

For example here is a simple Winforms UI I crafted with a few Expressions to visualize and each one just gets set to the PropertyGrid SelectedObject when selected from the list

image

Ok its not perfect but it is good enough to help you out

Here is the relevant code from the simple Winforms UI

Expression<Func<string, string, int>> fun1 = (s1, s2) => s1.Length - s2.Length;

TypeDescriptor.AddAttributes(typeof(Expression),
    new TypeConverterAttribute(typeof(ExpandableObjectConverter)));


propertyGrid1.SelectedObject = fun1;

2 thoughts on “Nice little trick when working with Expression API

Leave a comment