tags:

views:

82

answers:

2

I have a method Get on a type MyType1 accepting a Func<MyType2, bool> as a parameter.

An example of its use:

mytype1Instance.Get(x => x.Guid == guid));

I would like create a stub implementation of the method Get that examines the incoming lambda expression and determines what the value of guid is. Clearly the lambda could be "anything", but I'm happy for the stub to make an assumption about the lambda, that it is trying to match on the Guid property.

How can I do this? I suspect it involves the use of the built-in Expression type?

+2  A: 
public void Get<T>(Expression<Func<T,bool>> expr)
{
  // look at expr
}
leppie
+1  A: 

Take a look at Typed Reflector, which is a simple single-source-file component that provides a bridge from strongly typed member access to corresponding MemberInfo instances.

Even if you may not be able to use it as, it should give you a good idea about what you can do with Expressions.

Mark Seemann
Thanks, looks useful. Currently struggling with converting the Func<MyType2, bool> to an Expression for analysis.
Ben Aston
@Ben: I don't think you always have to initialize the lambda expression to an Expression immediately. Converting a Func (compiled IL code) to an Expression would basically be decompilation, which is hard and likely to not be supported. Remember that lambda expressions by themselves are not Func or any other delegate type. It's only when you assign them to a variable or pass them to a method that they gain their specific meaning. Hence leppie's answer.
Joren
Convert a Func<T,bool>, f, to an Expression, e: `Expression<Func<T,bool>> e = x => f(x);`
Ben Aston