views:

19

answers:

1

I'm trying to write an expression that will call ToString on a property and assign it's value to a local variable. However, calling ToString on a object instance w/ an overload of ToString, causes an exception of "Ambigous Match Found" to be thrown. Here's an example:

var result = Expression.Variable(typeof(string), "result");
var matchTypeParameter = Expression.Parameter(typeof(MatchType), "matchType");
var targetProperty = Expression.Property(leadParameter, target);

var exp = Expression.Block(
  //Add the local current value variable
  new[] { result },

  //Get the target value
  Expression.Assign(result, Expression.Call(targetProperty, typeof(string).GetMethod("ToString"), null))

);

How can I call ToString if the instance has overloads for it? Thanks!

+1  A: 

Replace:

typeof(string).GetMethod("ToString")

With:

typeof(string).GetMethod("ToString", Type.EmptyTypes)

In other words, get the method named "ToString" that takes zero arguments (empty type array).

Kirk Woll
This was exactly what I was looking for, Thanks! I've never heard of Type.EmptyTypes before. Is there a reflection book that discusses things like this that you would recommend?
James Alexander
Type.EmptyTypes is just shorthand (and slighly more efficient than) `new Type[0]`. Sorry, I'm not a book person, but you'll learn a *lot* just perusing the source code to `MethodInfo`, `FieldInfo`, and `Type` (in addition to all the methods in `Expression`).
Kirk Woll